collab.go

 1package cmd
 2
 3import (
 4	"github.com/charmbracelet/soft-serve/pkg/access"
 5	"github.com/charmbracelet/soft-serve/pkg/backend"
 6	"github.com/spf13/cobra"
 7)
 8
 9func collabCommand() *cobra.Command {
10	cmd := &cobra.Command{
11		Use:     "collab",
12		Aliases: []string{"collabs", "collaborator", "collaborators"},
13		Short:   "Manage collaborators",
14	}
15
16	cmd.AddCommand(
17		collabAddCommand(),
18		collabRemoveCommand(),
19		collabListCommand(),
20	)
21
22	return cmd
23}
24
25func collabAddCommand() *cobra.Command {
26	cmd := &cobra.Command{
27		Use:               "add REPOSITORY USERNAME [LEVEL]",
28		Short:             "Add a collaborator to a repo",
29		Long:              "Add a collaborator to a repo. LEVEL can be one of: no-access, read-only, read-write, or admin-access. Defaults to read-write.",
30		Args:              cobra.RangeArgs(2, 3),
31		PersistentPreRunE: checkIfReadableAndCollab,
32		RunE: func(cmd *cobra.Command, args []string) error {
33			ctx := cmd.Context()
34			be := backend.FromContext(ctx)
35			repo := args[0]
36			username := args[1]
37			level := access.ReadWriteAccess
38			if len(args) > 2 {
39				level = access.ParseAccessLevel(args[2])
40				if level < 0 {
41					return access.ErrInvalidAccessLevel
42				}
43			}
44
45			return be.AddCollaborator(ctx, repo, username, level)
46		},
47	}
48
49	return cmd
50}
51
52func collabRemoveCommand() *cobra.Command {
53	cmd := &cobra.Command{
54		Use:               "remove REPOSITORY USERNAME",
55		Args:              cobra.ExactArgs(2),
56		Short:             "Remove a collaborator from a repo",
57		PersistentPreRunE: checkIfReadableAndCollab,
58		RunE: func(cmd *cobra.Command, args []string) error {
59			ctx := cmd.Context()
60			be := backend.FromContext(ctx)
61			repo := args[0]
62			username := args[1]
63
64			return be.RemoveCollaborator(ctx, repo, username)
65		},
66	}
67
68	return cmd
69}
70
71func collabListCommand() *cobra.Command {
72	cmd := &cobra.Command{
73		Use:               "list REPOSITORY",
74		Short:             "List collaborators for a repo",
75		Args:              cobra.ExactArgs(1),
76		PersistentPreRunE: checkIfReadableAndCollab,
77		RunE: func(cmd *cobra.Command, args []string) error {
78			ctx := cmd.Context()
79			be := backend.FromContext(ctx)
80			repo := args[0]
81			collabs, err := be.Collaborators(ctx, repo)
82			if err != nil {
83				return err //nolint:wrapcheck
84			}
85
86			for _, c := range collabs {
87				cmd.Println(c)
88			}
89
90			return nil
91		},
92	}
93
94	return cmd
95}