GitLabgitlab-org
cli
main
1package cmdutils
3import (
4 "cmp"
5 "errors"
6 "fmt"
7 "net/url"
8 "sort"
9 "strings"
11 "gitlab.com/gitlab-org/cli/internal/config"
12 "gitlab.com/gitlab-org/cli/internal/dbg"
13 "gitlab.com/gitlab-org/cli/internal/git"
14 "gitlab.com/gitlab-org/cli/internal/glinstance"
15 "gitlab.com/gitlab-org/cli/internal/glrepo"
16)
18// ErrNoGitRemotes indicates the repository has no git remotes configured.
19// Distinct from git.ErrNotAGitRepository: there is a repo, it just has
20// nothing to resolve against.
21var ErrNoGitRemotes = errors.New("no git remotes found")
23type remoteResolver struct {
24 readRemotes func() (git.RemoteSet, error)
25 getConfig func() config.Config
26 parseSSHConfig func() git.SSHAliasMap
27 defaultHostname string
28 // hostOverrideEnvVar names the environment variable that set the host
29 // override. When empty, the override came from the config file.
30 hostOverrideEnvVar string
31}
33func (rr *remoteResolver) Resolver(hostOverride string) func() (glrepo.Remotes, error) {
34 var cachedRemotes glrepo.Remotes
35 var remotesError error
37 return func() (glrepo.Remotes, error) {
38 if cachedRemotes != nil || remotesError != nil {
39 return cachedRemotes, remotesError
40 }
42 gitRemotes, err := rr.readRemotes()
43 if err != nil {
44 remotesError = err
45 return nil, err
46 }
47 if len(gitRemotes) == 0 {
48 remotesError = ErrNoGitRemotes
49 return nil, remotesError
50 }
52 cfg := rr.getConfig()
54 // Collect the configured hosts before translating the remotes, so a remote
55 // whose literal SSH host already matches a configured host can skip the
56 // ssh_config translation below.
57 knownHosts := map[string]struct{}{}
58 configuredHosts := map[string]struct{}{} // Only the accounts present in the config file.
59 sshHostMapping := map[string]string{} // Maps SSH hostnames to config keys
60 knownHosts[glinstance.DefaultHostname] = struct{}{}
61 if authenticatedHosts, err := cfg.Hosts(); err == nil {
62 for _, h := range authenticatedHosts {
63 // Config host lookups are case-sensitive: cfg.Hosts() returns the raw
64 // YAML keys and cfg.Get matches them literally, so keys go in verbatim.
65 knownHosts[h] = struct{}{}
66 configuredHosts[h] = struct{}{}
68 // The ssh_host value is only ever compared against a lower-cased remote
69 // host, so normalize it here to keep the two sides consistent.
70 if sshHost, _ := cfg.Get(h, "ssh_host"); sshHost != "" {
71 sshHostMapping[glinstance.NormalizeHostname(sshHost)] = h
72 }
73 }
74 }
76 sshTranslate := rr.parseSSHConfig().Translator()
77 resolvedRemotes := glrepo.TranslateRemotes(
78 gitRemotes,
79 func(u *url.URL) *url.URL {
80 if u.Scheme != "ssh" {
81 return u
82 }
83 // A remote whose literal SSH host is already a configured account (a
84 // config key or an entry's ssh_host) resolves to that account, exactly as
85 // an HTTPS remote would; only unknown hosts fall back to ssh_config
86 // translation. The default gitlab.com is deliberately excluded here: when
87 // it is not a configured account, an alias pointing it elsewhere is a
88 // redirect to another instance and must be followed, as git does.
89 // See https://gitlab.com/gitlab-org/cli/-/issues/8394.
90 host := glinstance.NormalizeHostname(u.Hostname())
91 if _, configured := configuredHosts[host]; configured {
92 return u
93 }
94 if _, mapped := sshHostMapping[host]; mapped {
95 return u
96 }
97 return sshTranslate(u)
98 },
99 rr.defaultHostname,
100 cfg,
101 )
103 // filter remotes to only those sharing a single, known hostname
104 var hostname string
105 cachedRemotes = glrepo.Remotes{}
106 sort.Sort(resolvedRemotes)
108 if hostOverride != "" {
109 for _, r := range resolvedRemotes {
110 repoHost := r.RepoHost()
111 if !strings.EqualFold(repoHost, hostOverride) {
112 // Check if this is an SSH host that maps to the override
113 if configHost, found := sshHostMapping[repoHost]; found && strings.EqualFold(configHost, hostOverride) {
114 r = &glrepo.Remote{
115 Remote: r.Remote,
116 Repo: glrepo.NewWithHost(r.RepoOwner(), r.RepoName(), configHost),
117 }
118 } else {
119 continue
120 }
121 }
122 cachedRemotes = append(cachedRemotes, r)
123 }
125 if len(cachedRemotes) > 0 {
126 return cachedRemotes, nil
127 }
129 // A config-file host only prefers a matching remote. It never rejects
130 // the others. See https://gitlab.com/gitlab-org/cli/-/issues/8595.
131 if envVar := rr.hostOverrideEnvVar; envVar != "" {
132 remotesError = errors.New("none of the git remotes configured for this repository correspond to the " + envVar + " environment variable. Try adding a matching remote or unsetting the variable.\n\n" +
133 envVar + " is currently set to " + hostOverride + "\n\nConfigured remotes: " + resolvedRemotes.UniqueHosts())
134 return nil, remotesError
135 }
136 dbg.Debug("config host " + hostOverride + " matches no git remote; resolving from remotes instead")
137 }
139 for _, r := range resolvedRemotes {
140 repoHost := r.RepoHost()
142 // Check if this is a known host or SSH host that maps to a config entry
143 if _, ok := knownHosts[repoHost]; !ok {
144 configHost, found := sshHostMapping[repoHost]
145 if !found {
146 // Unknown host - skip this remote
147 continue
148 }
149 // SSH host maps to a config entry — update both repoHost and r
150 // so that RepoHost() returns the API hostname and filtering works correctly
151 repoHost = configHost
152 r = &glrepo.Remote{
153 Remote: r.Remote,
154 Repo: glrepo.NewWithHost(r.RepoOwner(), r.RepoName(), configHost),
155 }
156 }
158 if repoHost != hostname && hostname != "" {
159 continue
160 }
162 hostname = cmp.Or(hostname, repoHost)
163 cachedRemotes = append(cachedRemotes, r)
164 }
166 if len(cachedRemotes) == 0 {
167 var advice string
168 if hints := sshHostHints(resolvedRemotes, configuredHosts); hints != "" {
169 advice = "\n\n" + hints
170 } else {
171 advice = " Please use `glab auth login` to authenticate and configure a new host for glab.\n\n"
172 }
173 remotesError = errors.New("none of the git remotes configured for this repository point to a known GitLab host." +
174 advice + "Configured remotes: " + resolvedRemotes.UniqueHosts())
175 return nil, remotesError
176 }
177 return cachedRemotes, nil
178 }
179}
181// sshHostHints suggests setting ssh_host for each SSH remote host that is a
182// subdomain of a configured host, such as ssh.gitlab.example.com for
183// gitlab.example.com. glab never makes that mapping itself, because the
184// subdomain may be a separate instance.
185func sshHostHints(remotes glrepo.Remotes, configuredHosts map[string]struct{}) string {
186 var hints strings.Builder
187 seen := map[string]struct{}{}
188 for _, r := range remotes {
189 if r.FetchURL == nil || r.FetchURL.Scheme != "ssh" {
190 continue
191 }
192 remoteHost := r.RepoHost()
193 if _, ok := seen[remoteHost]; ok {
194 continue
195 }
196 seen[remoteHost] = struct{}{}
198 var parent string
199 for h := range configuredHosts {
200 if strings.HasSuffix(remoteHost, "."+glinstance.NormalizeHostname(h)) && len(h) > len(parent) {
201 parent = h
202 }
203 }
204 if parent == "" {
205 continue
206 }
207 fmt.Fprintf(&hints, "If %s is the SSH host of %s, run:\n\n glab config set ssh_host %s --host %s\n\n",
208 remoteHost, parent, remoteHost, parent)
209 }
210 return hints.String()
211}
213// WithGitRequiredHint adds a hint to err, an error from resolving the
214// repository from the git remote, when git isn't on the PATH.
215func WithGitRequiredHint(executor Executor, err error) error {
216 if _, lookErr := executor.LookPath("git"); lookErr != nil {
217 return fmt.Errorf("%w. git is required", err)
218 }
219 return err
220}
Diagnostics6 git calls · 351 ms
CallStatusSizeTime0351 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=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 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
fetchtree:0 · deepen 1020032 KiB · 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=32926 git.response.cache=HIT git.response.duration_ms=2 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
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=2 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:02001.2 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=343 git.response.bytes=1238 git.response.cache=HIT git.response.duration_ms=2 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 KiB343 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2710 git.response.cache=MISS git.response.duration_ms=343 git.fetch.wants=b5d5f114d7e25a878472709460a70059d616b3a1 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=2710 git.pkt.payload.max=2683 git.sideband.band1.bytes=2683 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
- a5e1323aebcfa9fe
- Request
- be81fd5a…
- 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