GitLabgitlab-org

cli

main
ply8 git calls215 ms100 KiB5 cachedprotocol v2
227 lines7.2 KiBRaw
1// Package serviceaccountutils holds the scope resolution, account lookup and
2// display code shared by the service-account subcommands.
3package serviceaccountutils
5import (
6 "context"
7 "errors"
8 "fmt"
9 "iter"
10 "strconv"
11 "strings"
13 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
15 "gitlab.com/gitlab-org/cli/internal/api"
16 "gitlab.com/gitlab-org/cli/internal/glrepo"
17 "gitlab.com/gitlab-org/cli/internal/iostreams"
18 "gitlab.com/gitlab-org/cli/internal/tableprinter"
21// Scope is the group or the project whose service accounts a command acts on.
22// Exactly one of Group and Project is set.
23type Scope struct {
24 Group string
25 Project string
28func (s Scope) String() string {
29 if s.Group != "" {
30 return "group " + s.Group
31 }
32 return "project " + s.Project
35// NewClient resolves the scope and builds the API client for it. group is the
36// value returned by cmdutils.GroupOverride; when it is empty the base repository
37// is the scope.
38func NewClient(
39 baseRepo func() (glrepo.Interface, error),
40 apiClient func(repoHost string) (*api.Client, error),
41 group string,
42) (*gitlab.Client, Scope, error) {
43 // The group scope works outside a repository, so a missing base repo is only
44 // fatal for the project scope. Fail before building a client that would be
45 // discarded, so the caller sees why the repository was needed.
46 repo, repoErr := baseRepo()
47 if group == "" && repoErr != nil {
48 return nil, Scope{}, repoErr
49 }
51 var repoHost string
52 if repoErr == nil {
53 repoHost = repo.RepoHost()
54 }
56 c, err := apiClient(repoHost)
57 if err != nil {
58 return nil, Scope{}, err
59 }
61 if group != "" {
62 return c.Lab(), Scope{Group: group}, nil
63 }
64 return c.Lab(), Scope{Project: repo.FullName()}, nil
67// Account is the part of a service account common to the group and the project
68// API types, used for text output.
69type Account struct {
70 ID int64
71 Username string
72 Name string
73 Email string
74 UnconfirmedEmail string
77// FromGroup converts a group service account to an Account.
78func FromGroup(a *gitlab.GroupServiceAccount) Account {
79 return Account{ID: a.ID, Username: a.UserName, Name: a.Name, Email: a.Email, UnconfirmedEmail: a.UnconfirmedEmail}
82// FromProject converts a project service account to an Account.
83func FromProject(a *gitlab.ProjectServiceAccount) Account {
84 return Account{ID: a.ID, Username: a.Username, Name: a.Name, Email: a.Email, UnconfirmedEmail: a.UnconfirmedEmail}
87// OrDash renders an empty field as "-", matching the other token and
88// deploy-token tables.
89func OrDash(s string) string {
90 if s == "" {
91 return "-"
92 }
93 return s
96// PrintDetails prints a service account as a two-column table. The unconfirmed
97// email row appears only while a custom email address awaits confirmation.
98func PrintDetails(io *iostreams.IOStreams, a Account) {
99 c := io.Color()
100 table := tableprinter.NewTablePrinter()
101 table.AddRow(c.Bold("ID"), a.ID)
102 table.AddRow(c.Bold("Username"), a.Username)
103 table.AddRow(c.Bold("Name"), OrDash(a.Name))
104 table.AddRow(c.Bold("Email"), OrDash(a.Email))
105 if a.UnconfirmedEmail != "" {
106 table.AddRow(c.Bold("Unconfirmed Email"), a.UnconfirmedEmail)
107 }
108 io.LogInfof("%s", table.Render())
111const perPage = 100
113func groupPages(ctx context.Context, client *gitlab.Client, group string) func(gitlab.PaginationOptionFunc) ([]*gitlab.GroupServiceAccount, *gitlab.Response, error) {
114 opts := &gitlab.ListServiceAccountsOptions{ListOptions: gitlab.ListOptions{PerPage: perPage}}
115 return func(p gitlab.PaginationOptionFunc) ([]*gitlab.GroupServiceAccount, *gitlab.Response, error) {
116 return client.Groups.ListServiceAccounts(group, opts, p, gitlab.WithContext(ctx))
117 }
120func projectPages(ctx context.Context, client *gitlab.Client, project string) func(gitlab.PaginationOptionFunc) ([]*gitlab.ProjectServiceAccount, *gitlab.Response, error) {
121 opts := &gitlab.ListProjectServiceAccountsOptions{ListOptions: gitlab.ListOptions{PerPage: perPage}}
122 return func(p gitlab.PaginationOptionFunc) ([]*gitlab.ProjectServiceAccount, *gitlab.Response, error) {
123 return client.Projects.ListProjectServiceAccounts(project, opts, p, gitlab.WithContext(ctx))
124 }
127// List returns every service account in the scope, both as the raw API slice
128// for JSON output and as Accounts for text output.
129func List(ctx context.Context, client *gitlab.Client, scope Scope) (any, []Account, error) {
130 if scope.Group != "" {
131 raw, err := gitlab.ScanAndCollect(groupPages(ctx, client, scope.Group))
132 if err != nil {
133 return nil, nil, err
134 }
135 accounts := make([]Account, 0, len(raw))
136 for _, a := range raw {
137 accounts = append(accounts, FromGroup(a))
138 }
139 return raw, accounts, nil
140 }
142 raw, err := gitlab.ScanAndCollect(projectPages(ctx, client, scope.Project))
143 if err != nil {
144 return nil, nil, err
145 }
146 accounts := make([]Account, 0, len(raw))
147 for _, a := range raw {
148 accounts = append(accounts, FromProject(a))
149 }
150 return raw, accounts, nil
153// ParseID reports whether an <id|username> argument is an ID. A numeric
154// argument is always an ID, and is rejected when it is below 1 or does not fit
155// in an int64.
156func ParseID(ref string) (int64, bool, error) {
157 return parseID(ref, "service account")
160func parseID(ref, kind string) (int64, bool, error) {
161 id, err := strconv.ParseInt(ref, 10, 64)
162 switch {
163 case err == nil && id > 0:
164 return id, true, nil
165 case err == nil || errors.Is(err, strconv.ErrRange):
166 return 0, false, fmt.Errorf("invalid %s ID %q", kind, ref)
167 }
168 return 0, false, nil
171// ResolveID returns the ID of the service account an <id|username> argument
172// names. Only a username costs a request.
173func ResolveID(ctx context.Context, client *gitlab.Client, scope Scope, ref string) (int64, error) {
174 id, isID, err := ParseID(ref)
175 if err != nil || isID {
176 return id, err
177 }
179 _, account, err := FindByUsername(ctx, client, scope, ref)
180 if err != nil {
181 return 0, err
182 }
183 return account.ID, nil
186// FindByUsername returns the service account with the given username, both as
187// the raw API object for JSON output and as an Account for text output. The
188// list endpoints accept no username filter, so the accounts are matched page by
189// page, stopping at the first match.
190func FindByUsername(ctx context.Context, client *gitlab.Client, scope Scope, username string) (any, Account, error) {
191 var (
192 raw any
193 account Account
194 found bool
195 err error
196 )
197 if scope.Group != "" {
198 var item *gitlab.GroupServiceAccount
199 item, account, found, err = find(gitlab.Scan2(groupPages(ctx, client, scope.Group)), FromGroup, username)
200 raw = item
201 } else {
202 var item *gitlab.ProjectServiceAccount
203 item, account, found, err = find(gitlab.Scan2(projectPages(ctx, client, scope.Project)), FromProject, username)
204 raw = item
205 }
206 if err != nil {
207 return nil, Account{}, err
208 }
209 if !found {
210 return nil, Account{}, fmt.Errorf("no service account with username %q in %s", username, scope)
211 }
212 return raw, account, nil
215func find[T any](accounts iter.Seq2[T, error], toAccount func(T) Account, username string) (T, Account, bool, error) {
216 var zero T
217 for item, err := range accounts {
218 if err != nil {
219 return zero, Account{}, false, err
220 }
221 // GitLab treats usernames case-insensitively.
222 if a := toAccount(item); strings.EqualFold(a.Username, username) {
223 return item, a, true, nil
224 }
225 }
226 return zero, Account{}, false, nil
Diagnostics8 git calls · 215 ms
CallStatusSizeTime0215 ms
discover200185 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
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 KiB2 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=UPDATING
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 · hit5 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=32926
git.response.cache=HIT
git.response.duration_ms=5
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=44
Open pack map
fetchtree:02001.8 KiB · hit2 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=2
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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200322 B · hit1 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=322
git.response.cache=HIT
git.response.duration_ms=1
git.fetch.filter=tree:0
git.fetch.wants=ba2caccf6c55211c6b29b98f40c2358479d91b1f
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=322
git.pkt.payload.max=295
git.sideband.band1.bytes=295
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=295
git.pack.trailer=3488e558d4708096e879feba968e084c249dbe22
Open pack map
fetchtree:0200207 B · 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=207
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=46257722a5d9837ad7305a4a6942623f79e26348
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=207
git.pkt.payload.max=180
git.sideband.band1.bytes=180
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=180
git.pack.trailer=49c3336eecdc11d5831924e911d2e17735206333
Open pack map
fetch2002.4 KiB204 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=204
git.response.bytes=2448
git.response.cache=MISS
git.response.duration_ms=204
git.fetch.wants=d890f9774f0998c9b07f5a151ae1df0cbaeb28fc
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=2448
git.pkt.payload.max=2421
git.sideband.band1.bytes=2421
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
a5e3588b79392c38
Request
b366f6bd…
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