GitLabgitlab-org
cli
main
1package cmdutils
3import (
4 "context"
5 "fmt"
6 "slices"
7 "strings"
8 "sync"
10 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
12 "gitlab.com/gitlab-org/cli/internal/api"
13 "gitlab.com/gitlab-org/cli/internal/config"
14 "gitlab.com/gitlab-org/cli/internal/dbg"
15 "gitlab.com/gitlab-org/cli/internal/git"
16 "gitlab.com/gitlab-org/cli/internal/glinstance"
17 "gitlab.com/gitlab-org/cli/internal/glrepo"
18 "gitlab.com/gitlab-org/cli/internal/iostreams"
19 "gitlab.com/gitlab-org/cli/internal/utils"
20)
22// Factory is a way to obtain core tools for the commands.
23// Safe for concurrent use.
24type Factory interface {
25 RepoOverride(repo string) error
26 ApiClient(repoHost string) (*api.Client, error)
27 // GitLabClient returns an HTTP client that is initialize with the host from BaseRepo.
28 // You must only use GitLabClient if your command is tied to a single repository,
29 // otherwise use ApiClient
30 GitLabClient() (*gitlab.Client, error)
31 BaseRepo() (glrepo.Interface, error)
32 Remotes() (glrepo.Remotes, error)
33 Config() config.Config
34 Branch() (string, error)
35 IO() *iostreams.IOStreams
36 DefaultHostname() string
37 BuildInfo() api.BuildInfo
38 Executor() Executor
39 GitRunner() git.GitRunner
40}
42type DefaultFactory struct {
43 io *iostreams.IOStreams
44 config config.Config
45 resolveRepos bool
46 buildInfo api.BuildInfo
47 defaultHostname string
48 defaultProtocol string
49 transports *api.TransportCache
50 hostEnvVar string
51 // envTokenWarned holds the hosts warnIfEnvTokenWithheld already warned
52 // about, since one command can build several clients for the same host.
53 envTokenWarned sync.Map
55 mu sync.Mutex // protects the fields below
56 // cachedBaseRepo if set is the SSoT of the repository to use in BaseRepo(), GitLabClient() and other factory function that require a repository.
57 // This is also being set for a repo override.
58 cachedBaseRepo glrepo.Interface
59}
61func NewFactory(io *iostreams.IOStreams, resolveRepos bool, cfg config.Config, buildInfo api.BuildInfo) *DefaultFactory {
62 f := &DefaultFactory{
63 io: io,
64 config: cfg,
65 resolveRepos: resolveRepos,
66 buildInfo: buildInfo,
67 defaultHostname: glinstance.DefaultHostname,
68 defaultProtocol: glinstance.DefaultProtocol,
69 transports: api.NewTransportCache(),
70 }
72 // Fetch the custom host config from env vars, then local config.yml, then global config,yml.
73 customGLHost, hostSource, _ := cfg.GetWithSource("", "host", true)
74 if slices.Contains(config.EnvKeyEquivalence("host"), hostSource) {
75 f.hostEnvVar = hostSource
76 }
77 if customGLHost != "" {
78 if utils.IsValidURL(customGLHost) {
79 var protocol string
80 customGLHost, protocol = glinstance.StripHostProtocol(customGLHost)
81 f.defaultProtocol = protocol
82 }
83 f.defaultHostname = customGLHost
84 }
86 baseRepo, err := f.BaseRepo()
87 if err == nil {
88 f.defaultHostname = baseRepo.RepoHost()
89 }
91 return f
92}
94func (f *DefaultFactory) DefaultHostname() string {
95 return f.defaultHostname
96}
98func (f *DefaultFactory) RepoOverride(repo string) error {
99 if repo == "" {
100 return nil
101 }
103 f.mu.Lock()
104 defer f.mu.Unlock()
105 baseRepo, err := glrepo.FromFullName(repo, f.defaultHostname, f.config)
106 if err != nil {
107 return err // return the error if repo was overridden.
108 }
109 f.cachedBaseRepo = baseRepo
110 return nil
111}
113func (f *DefaultFactory) ApiClient(repoHost string) (*api.Client, error) {
114 if repoHost == "" {
115 repoHost = f.defaultHostname
116 }
117 c, err := api.NewClientFromConfig(repoHost, f.config, false, f.buildInfo.UserAgent(), api.WithTransportCache(f.transports))
118 if err != nil {
119 return nil, err
120 }
121 f.warnIfEnvTokenWithheld(repoHost)
122 return c, nil
123}
125// warnIfEnvTokenWithheld reports a credential environment variable that
126// config.IsTrustedHost withheld from repoHost, which would otherwise silently
127// leave the command unauthenticated.
128func (f *DefaultFactory) warnIfEnvTokenWithheld(repoHost string) {
129 if f.io == nil || config.IsTrustedHost(f.config, repoHost) {
130 return
131 }
132 // is_oauth2 is a header-scheme flag, not a standalone credential: when it
133 // is withheld alone the credential it decorates is also withheld and warned
134 // about, so a second warning would be noise.
135 var sources []string
136 for _, key := range []string{"token", "job_token"} {
137 if _, source := config.GetFromEnvWithSource(key); source != "" {
138 sources = append(sources, source)
139 }
140 }
141 if len(sources) == 0 {
142 return
143 }
144 if _, warned := f.envTokenWarned.LoadOrStore(repoHost, struct{}{}); warned {
145 return
146 }
147 c := f.io.Color()
148 f.io.LogErrorf("%s %s is set, but %q is neither the default host nor a configured host, so glab did not send the credential to it. To authenticate to this host, run %s.\n",
149 c.WarnIcon(), strings.Join(sources, ", "), repoHost, c.Bold("glab auth login --hostname "+repoHost))
150}
152func (f *DefaultFactory) GitLabClient() (*gitlab.Client, error) {
153 // TODO: the above code is a safety net for the factory changes introduced with
154 // https://gitlab.com/gitlab-org/cli/-/merge_requests/2181
155 // Eventually, we should make the factory independent of the repository a command
156 // uses and move that logic into a separate repository resolver.
157 // The factory should only be used to create things that to not have a state.
158 // Currently, the base repository is treated as state.
159 // Use the following code if you want to remove the safety net:
160 // repo, err := f.BaseRepo()
161 // if err != nil {
162 // return nil, err
163 // }
164 var repoHost string
165 repo, err := f.BaseRepo()
166 switch err {
167 case nil:
168 repoHost = repo.RepoHost()
169 default:
170 repoHost = f.defaultHostname
171 dbg.Debug("The current command request Factory.GitLabClient() without being able to resolve a base repository. The command should probably use Factory.ApiClient() instead")
172 }
174 c, err := api.NewClientFromConfig(repoHost, f.config, false, f.buildInfo.UserAgent(), api.WithTransportCache(f.transports))
175 if err != nil {
176 return nil, err
177 }
178 f.warnIfEnvTokenWithheld(repoHost)
180 return c.Lab(), nil
181}
183func (f *DefaultFactory) BaseRepo() (glrepo.Interface, error) {
184 f.mu.Lock()
185 defer f.mu.Unlock()
187 cachedBaseRepo := f.cachedBaseRepo
188 if cachedBaseRepo != nil {
189 return cachedBaseRepo, nil
190 }
192 baseRepo, err := f.resolveBaseRepoFromRemotes(context.Background())
193 if err != nil {
194 return nil, err
195 }
197 f.cachedBaseRepo = baseRepo
198 return f.cachedBaseRepo, nil
199}
201func (f *DefaultFactory) resolveBaseRepoFromRemotes(ctx context.Context) (glrepo.Interface, error) {
202 remotes, err := f.Remotes()
203 if err != nil {
204 return nil, err
205 }
207 if !f.resolveRepos {
208 return remotes[0], nil
209 }
211 ac, err := api.NewClientFromConfig(remotes[0].RepoHost(), f.config, false, f.buildInfo.UserAgent(), api.WithTransportCache(f.transports))
212 if err != nil {
213 return nil, err
214 }
216 repoContext, err := glrepo.ResolveRemotesToRepos(remotes, ac.Lab(), f.defaultHostname, f.config)
217 if err != nil {
218 return nil, err
219 }
221 baseRepo, err := repoContext.BaseRepo(ctx, f.io)
222 if err != nil {
223 return nil, err
224 }
226 return baseRepo, nil
227}
229func (f *DefaultFactory) Remotes() (glrepo.Remotes, error) {
230 hostOverride := ""
231 if !strings.EqualFold(glinstance.DefaultHostname, f.defaultHostname) {
232 hostOverride = f.defaultHostname
233 }
234 rr := &remoteResolver{
235 readRemotes: git.Remotes,
236 getConfig: f.Config,
237 parseSSHConfig: git.ParseSSHConfig,
238 defaultHostname: f.defaultHostname,
239 hostOverrideEnvVar: f.hostEnvVar,
240 }
241 fn := rr.Resolver(hostOverride)
242 return fn()
243}
245func (f *DefaultFactory) Config() config.Config {
246 return f.config
247}
249func (f *DefaultFactory) Branch() (string, error) {
250 currentBranch, err := git.CurrentBranch()
251 if err != nil {
252 return "", fmt.Errorf("could not determine current branch: %w", err)
253 }
254 return currentBranch, nil
255}
257func (f *DefaultFactory) IO() *iostreams.IOStreams {
258 return f.io
259}
261func (f *DefaultFactory) BuildInfo() api.BuildInfo {
262 return f.buildInfo
263}
265func (f *DefaultFactory) Executor() Executor {
266 return &factoryExecutor{
267 io: f.io,
268 }
269}
271func (f *DefaultFactory) GitRunner() git.GitRunner {
272 return git.NewGitCommand(f.Executor())
273}
Diagnostics6 git calls · 37 ms
CallStatusSizeTime037 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 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 · hit3 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=3 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.2 KiB · hit1 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=30 git.response.bytes=1238 git.response.cache=HIT git.response.duration_ms=1 git.fetch.filter=tree:0 git.fetch.wants=c10f4b8b760c3fec7ed8ca85e428d5bc523f8e17 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=1238 git.pkt.payload.max=1211 git.sideband.band1.bytes=1211 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1211 git.pack.trailer=7373aa350f2a611db7d4116eb1450c92f18a27caOpen pack map
fetch2002.6 KiB · hit30 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2659 git.response.cache=HIT git.response.duration_ms=30 git.fetch.wants=e5a71b84be7f6ea0ab17408553f62acdb2c93e29 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=2659 git.pkt.payload.max=2632 git.sideband.band1.bytes=2632 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
- a5e153ff4d380acb
- Request
- d4806eec…
- 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