GitLabgitlab-org
cli
main
1package add
3import (
4 "fmt"
5 "strconv"
7 "github.com/MakeNowJust/heredoc/v2"
8 "github.com/spf13/cobra"
10 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
12 "gitlab.com/gitlab-org/cli/internal/cmdutils"
13 "gitlab.com/gitlab-org/cli/internal/glrepo"
14 "gitlab.com/gitlab-org/cli/internal/iostreams"
15 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
16)
18type options struct {
19 role string
20 roleID int64
21 expiresAt string
22 userID int
23 username string
25 baseRepo func() (glrepo.Interface, error)
26 gitlabClient func() (*gitlab.Client, error)
27 io *iostreams.IOStreams
28}
30var roles = map[string]gitlab.AccessLevelValue{
31 "guest": gitlab.GuestPermissions,
32 "reporter": gitlab.ReporterPermissions,
33 "developer": gitlab.DeveloperPermissions,
34 "maintainer": gitlab.MaintainerPermissions,
35 "owner": gitlab.OwnerPermissions,
36}
38func newOptions(f cmdutils.Factory) *options {
39 return &options{
40 io: f.IO(),
41 baseRepo: f.BaseRepo,
42 gitlabClient: f.GitLabClient,
43 }
44}
46func NewCmd(f cmdutils.Factory) *cobra.Command {
47 opts := newOptions(f)
49 cmd := &cobra.Command{
50 Use: "add [flags]",
51 Short: `Add a member to the project.`,
52 Long: heredoc.Docf(`
53 Add a member to the project with the specified role.
55 Roles:
57 - guest (10): Can view the project.
58 - reporter (20): Can view and create issues.
59 - developer (30): Can push to non-protected branches.
60 - maintainer (40): Can manage the project.
61 - owner (50): Full access to the project.
63 For custom roles, use %[1]s--role-id%[1]s with the ID of a custom role defined in the project or group.
64 If the custom role does not exist, an error is returned.
65 `, "`"),
66 Example: heredoc.Doc(`
67 # Add a user as a developer
68 glab repo members add --username=john.doe --role=developer
69 # Add a user as a maintainer with expiration date
70 glab repo members add --username=jane.smith --role=maintainer --expires-at=2024-12-31
71 # Add a user by ID
72 glab repo members add --user-id=123 --role=reporter
73 # Add a user with a custom role
74 glab repo members add --username=john.doe --role-id=101`),
75 Args: cobra.NoArgs,
76 ValidArgsFunction: cobra.NoFileCompletions,
77 Annotations: map[string]string{
78 mcpannotations.Destructive: "true",
79 },
80 RunE: func(cmd *cobra.Command, args []string) error {
81 if err := opts.validate(); err != nil {
82 return err
83 }
84 return opts.run()
85 },
86 }
88 cmdutils.EnableRepoOverride(cmd, f)
90 fl := cmd.Flags()
91 fl.StringVarP(&opts.role, "role", "r", "developer", "Role for the user (guest, reporter, developer, maintainer, owner)")
92 fl.Int64Var(&opts.roleID, "role-id", 0, "ID of a custom role defined in the project or group.")
93 fl.StringVarP(&opts.expiresAt, "expires-at", "e", "", "Expiration date for the membership (YYYY-MM-DD)")
94 fl.IntVarP(&opts.userID, "user-id", "u", 0, "User ID instead of username.")
95 fl.StringVarP(&opts.username, "username", "", "", "Username instead of user-id.")
96 cmd.MarkFlagsMutuallyExclusive("username", "user-id")
97 cmd.MarkFlagsMutuallyExclusive("role", "role-id")
99 return cmd
100}
102func (o *options) validate() error {
103 if o.username == "" && o.userID == 0 {
104 return fmt.Errorf("either username or user-id must be specified")
105 }
107 if o.roleID != 0 {
108 // Custom role: no further validation here, but API will validate
109 if o.role != "developer" { // Reset to default if role-id is set
110 o.role = ""
111 }
112 } else {
113 if _, ok := roles[o.role]; !ok {
114 return fmt.Errorf("invalid role: %s. Valid roles are: guest, reporter, developer, maintainer, owner", o.role)
115 }
116 }
118 return nil
119}
121func (o *options) run() error {
122 client, err := o.gitlabClient()
123 if err != nil {
124 return err
125 }
127 repo, err := o.baseRepo()
128 if err != nil {
129 return err
130 }
132 var userIDToAdd int
133 var userIdentifier string
135 switch {
136 case o.userID != 0:
137 userIDToAdd = o.userID
138 userIdentifier = strconv.Itoa(o.userID)
139 case o.username != "":
140 // Get user ID from username
141 users, _, err := client.Users.ListUsers(&gitlab.ListUsersOptions{
142 Username: &o.username,
143 })
144 if err != nil {
145 return fmt.Errorf("failed to find user %s: %w", o.username, err)
146 }
147 switch len(users) {
148 case 0:
149 return fmt.Errorf("user %s not found", o.username)
150 case 1:
151 default:
152 return fmt.Errorf("multiple users found with username %s", o.username)
153 }
155 userIDToAdd = int(users[0].ID)
156 userIdentifier = o.username
157 }
159 addOptions := &gitlab.AddProjectMemberOptions{}
161 if o.roleID != 0 {
162 addOptions.MemberRoleID = new(o.roleID)
163 } else {
164 role := roles[o.role]
165 addOptions.AccessLevel = new(role)
166 }
168 if o.expiresAt != "" {
169 addOptions.ExpiresAt = new(o.expiresAt)
170 }
172 addOptions.UserID = new(userIDToAdd)
173 member, _, err := client.ProjectMembers.AddProjectMember(repo.FullName(), addOptions)
174 if err != nil {
175 return fmt.Errorf("failed to add member %s: %w", userIdentifier, err)
176 }
178 c := o.io.Color()
179 if o.roleID != 0 {
180 o.io.LogInfof("%s Successfully added %s with custom role ID %d to %s\n",
181 c.GreenCheck(),
182 c.Bold(member.Username),
183 o.roleID,
184 c.Bold(repo.FullName()))
185 } else {
186 o.io.LogInfof("%s Successfully added %s as %s to %s\n",
187 c.GreenCheck(),
188 c.Bold(member.Username),
189 c.Bold(o.role),
190 c.Bold(repo.FullName()))
191 }
193 if o.expiresAt != "" {
194 o.io.LogInfof(" Membership expires on: %s\n", o.expiresAt)
195 }
197 return nil
198}
Diagnostics9 git calls · 226 ms
CallStatusSizeTime0226 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=1 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchtree:02001.8 KiB · hit1 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=1 git.fetch.filter=tree:0 git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=1857 git.pkt.payload.max=1830 git.sideband.band1.bytes=1830 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1830 git.pack.trailer=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200614 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=614 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=3a89d0cfc8e81880c982180388e42e561a0b7eee git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=614 git.pkt.payload.max=587 git.sideband.band1.bytes=587 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=587 git.pack.trailer=eb8250f8e8340ff2fafc22c5aba90db34fd906a9Open pack map
fetchtree:0200198 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=198 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=ae4de5db0d32551153085c68d34eb0d395b7df5a git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=198 git.pkt.payload.max=171 git.sideband.band1.bytes=171 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=171 git.pack.trailer=b44c92e9fa6892fac61a2b92ee59f8711c1238cfOpen pack map
fetchtree:0200135 B · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=211 git.response.bytes=135 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=b798cf6d8a774b5f08277273be20975daff0dc4e git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=135 git.pkt.payload.max=108 git.sideband.band1.bytes=108 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=108 git.pack.trailer=5279d342a77d2176a49e3300458c8c67ca7fec29Open pack map
fetch2002.0 KiB211 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2042 git.response.cache=MISS git.response.duration_ms=211 git.fetch.wants=e720fda40bfaa4295f3f71af78139c9787b2094f git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2042 git.pkt.payload.max=2015 git.sideband.band1.bytes=2015 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://gitlab.com/gitlab-org/cli
- Ref
- refs/heads/main
- Commit
- 0dd7574dce9e385c5c30540e6c15657adc6bdce9
- cf-ray
- a5ea623a2f6eecd4
- Request
- 99bc2e4c…
- Protocol
- v2 · sha1
- Agent
- git/2.56.g1891de4-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format