GitLabgitlab-org
cli
main
1package glrepo
3import (
4 "errors"
5 "fmt"
6 "net/url"
7 "slices"
8 "strings"
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/git"
15 "gitlab.com/gitlab-org/cli/internal/glinstance"
16 "gitlab.com/gitlab-org/cli/internal/utils"
17)
19// RemoteURL returns correct git clone URL of a repo
20// based on the user's git_protocol preference
21func RemoteURL(project *gitlab.Project, protocol string) (string, error) {
22 remoteURL := project.HTTPURLToRepo
23 if protocol == "ssh" {
24 remoteURL = project.SSHURLToRepo
25 }
26 if err := git.ValidateRemoteURL(remoteURL); err != nil {
27 return "", err
28 }
29 return remoteURL, nil
30}
32// WikiRemoteURL returns the clone URL for a project's wiki repository.
33func WikiRemoteURL(project *gitlab.Project, protocol string) (string, error) {
34 remoteURL, err := RemoteURL(project, protocol)
35 if err != nil {
36 return "", err
37 }
38 return strings.TrimSuffix(remoteURL, ".git") + ".wiki.git", nil
39}
41// FullName returns the repo with its namespace (like profclems/glab). Respects group and subgroups names
42func FullNameFromURL(remoteURL string) (string, error) {
43 parts := strings.Split(remoteURL, "//")
45 switch len(parts) {
46 case 1:
47 // scp-like short syntax (e.g. git@gitlab.com...)
48 part := parts[0]
49 parts = strings.Split(part, ":")
50 case 2:
51 // other protocols (e.g. ssh://, http://, git://)
52 part := parts[1]
53 parts = strings.SplitN(part, "/", 2)
54 default:
55 return "", errors.New("cannot parse remote: " + remoteURL)
56 }
58 if len(parts) != 2 {
59 return "", errors.New("cannot parse remote: " + remoteURL)
60 }
61 repo := parts[1]
62 repo = strings.TrimSuffix(repo, "/")
63 repo = strings.TrimSuffix(repo, ".git")
64 return repo, nil
65}
67// Interface describes an object that represents a GitLab repository
68// Contains methods for these methods representing these placeholders for a
69// project path with :host/:group/:namespace/:repo
70// RepoHost = :host, RepoOwner = :group/:namespace, RepoNamespace = :namespace,
71// FullName = :group/:namespace/:repo, RepoGroup = :group, RepoName = :repo
72type Interface interface {
73 RepoName() string
74 RepoOwner() string
75 RepoNamespace() string
76 RepoGroup() string
77 RepoHost() string
78 FullName() string
79 Project(*gitlab.Client) (*gitlab.Project, error)
80}
82// New instantiates a GitLab repository from owner and repo name arguments
83func New(owner, repo, defaultHostname string) Interface {
84 return NewWithHost(owner, repo, defaultHostname)
85}
87// NewWithGroup instantiates a GitLab repository from group, namespace and repo name arguments
88func NewWithGroup(group, namespace, repo, hostname, defaultHostname string) Interface {
89 owner := fmt.Sprintf("%s/%s", group, namespace)
90 if hostname == "" {
91 return New(owner, repo, defaultHostname)
92 }
93 return NewWithHost(owner, repo, hostname)
94}
96// NewWithHost is like New with an explicit host name
97func NewWithHost(owner, repo, hostname string) Interface {
98 rp := &glRepo{
99 owner: owner,
100 name: repo,
101 fullname: fmt.Sprintf("%s/%s", owner, repo),
102 hostname: normalizeHostname(hostname),
103 }
104 if ri := strings.SplitN(owner, "/", 2); len(ri) == 2 {
105 rp.group = ri[0]
106 rp.namespace = ri[1]
107 } else {
108 rp.namespace = owner
109 }
110 return rp
111}
113// FromFullName extracts the GitLab repository information from the following
114// formats: "OWNER/REPO", "HOST/OWNER/REPO", "HOST/GROUP/NAMESPACE/REPO", and a full URL.
115func FromFullName(nwo string, defaultHostname string, cfg config.Config) (Interface, error) {
116 nwo = strings.TrimSpace(nwo)
117 // check if it's a valid git URL and parse it
118 if git.IsValidURL(nwo) {
119 u, err := git.ParseURL(nwo)
120 if err != nil {
121 return nil, err
122 }
123 return FromURL(u, defaultHostname, cfg)
124 }
125 // check if it is valid URL and parse it
126 if utils.IsValidURL(nwo) {
127 u, _ := url.Parse(nwo)
128 return FromURL(u, defaultHostname, cfg)
129 }
131 repo := nwo[strings.LastIndex(nwo, "/")+1:]
132 nwoWithoutRepo := strings.TrimSuffix(nwo[:strings.LastIndex(nwo, "/")+1], "/")
133 parts := strings.SplitN(nwoWithoutRepo, "/", 2)
135 if repo == "" {
136 return nil, fmt.Errorf(`expected the "[HOST/]OWNER/[NAMESPACE/]REPO" format, got %q`, nwo)
137 }
138 if slices.Contains(parts, "") {
139 return nil, fmt.Errorf(`expected the "[HOST/]OWNER/[NAMESPACE/]REPO" format, got %q`, nwo)
140 }
141 switch len(parts) {
142 case 2: // GROUP/NAMESPACE/REPO or HOST/OWNER/REPO or //HOST/GROUP/NAMESPACE/REPO
143 // First, checks if the first part matches the default instance host (i.e. gitlab.com) or the
144 // overridden default host (mostly from the GITLAB_HOST env variable)
145 if parts[0] == glinstance.DefaultHostname || parts[0] == defaultHostname {
146 return NewWithHost(parts[1], repo, normalizeHostname(parts[0])), nil
147 }
148 // Dots (.) are allowed in group names by GitLab.
149 // So we check if the first part contains a dot.
150 // However, it could be that the user is specifying a hostname but we can't be sure of that
151 // So we check in the list of authenticated hosts and see if it matches any
152 // if not, we assume it is a group name that contains a dot
153 // A colon cannot appear in a group path, so a host with a port but
154 // no dot (for example localhost:3000) is checked the same way.
155 if strings.ContainsAny(parts[0], ".:") && cfg != nil {
156 var rI Interface
157 hosts, _ := cfg.Hosts()
158 if slices.Contains(hosts, parts[0]) {
159 rI = NewWithHost(parts[1], repo, normalizeHostname(parts[0]))
160 }
161 if rI != nil {
162 return rI, nil
163 }
164 }
165 // if the first part is not a valid URL, and does not match an
166 // authenticated hostname then we assume it is in
167 // the format GROUP/NAMESPACE/REPO
168 return NewWithGroup(parts[0], parts[1], repo, "", defaultHostname), nil
169 case 1: // OWNER/REPO
170 return New(parts[0], repo, defaultHostname), nil
171 default:
172 return nil, fmt.Errorf(`expected the "[HOST/]OWNER/[NAMESPACE/]REPO" format, got %q`, nwo)
173 }
174}
176// FromURL extracts the GitLab repository information from a git remote URL
177func FromURL(u *url.URL, defaultHostname string, cfg config.Config) (Interface, error) {
178 if u.Hostname() == "" {
179 return nil, fmt.Errorf("no hostname detected")
180 }
182 urlPath := TrimSubfolder(u, cfg)
184 // Standard path parsing
185 urlPath = strings.TrimLeft(git.StripDotGit(urlPath), "/")
186 if urlPath == "" || !strings.Contains(urlPath, "/") {
187 return nil, fmt.Errorf("invalid path: %s", u.Path)
188 }
190 lastSlash := strings.LastIndex(urlPath, "/")
191 repo := urlPath[lastSlash+1:]
192 pathWithoutRepo := urlPath[:lastSlash]
194 if repo != "" && pathWithoutRepo != "" {
195 parts := strings.SplitN(pathWithoutRepo, "/", 2)
196 if len(parts) == 1 {
197 return NewWithHost(parts[0], repo, u.Host), nil
198 }
200 if len(parts) == 2 {
201 return NewWithGroup(parts[0], parts[1], repo, u.Host, defaultHostname), nil
202 }
203 }
204 return nil, fmt.Errorf("invalid path: %s", u.Path)
205}
207// TrimSubfolder returns u's path without its leading slash and without the
208// subfolder configured for u's host.
209func TrimSubfolder(u *url.URL, cfg config.Config) string {
210 // Retrieve subfolder from the injected config when available. The lookup is
211 // keyed on u.Host, not u.Hostname(): host entries are written with the port
212 // (`auth login --hostname example.com:8080`), and RepoHost carries the
213 // port too, so the API client resolves its own settings under the same key.
214 // Keying on the port-stripped hostname silently misses every setting for a
215 // ported instance.
216 var subfolder string
217 if cfg != nil {
218 subfolder, _ = cfg.Get(u.Host, "subfolder")
220 // Backward compatibility: extract subfolder from api_host if subfolder field is empty
221 if subfolder == "" {
222 apiHost, _ := cfg.Get(u.Host, "api_host")
223 if apiHost != "" && strings.Contains(apiHost, "/") {
224 parts := strings.SplitN(apiHost, "/", 2)
225 if len(parts) == 2 {
226 subfolder = parts[1]
227 }
228 }
229 }
230 }
232 urlPath := strings.TrimPrefix(u.Path, "/")
233 if subfolder != "" {
234 subfolderPrefix := strings.Trim(subfolder, "/") + "/"
235 if after, ok := strings.CutPrefix(urlPath, subfolderPrefix); ok {
236 urlPath = after
237 }
238 }
239 return urlPath
240}
242// www.gitlab.com is an alias of gitlab.com; other www. hosts may be
243// distinct instances (#8750).
244func normalizeHostname(h string) string {
245 h = strings.ToLower(h)
246 if rest, ok := strings.CutPrefix(h, "www."); ok {
247 if rest == glinstance.DefaultHostname || strings.HasPrefix(rest, glinstance.DefaultHostname+":") {
248 return rest
249 }
250 }
251 return h
252}
254// IsSame compares two GitLab repositories
255func IsSame(a, b Interface) bool {
256 if a == nil || b == nil {
257 return false
258 }
259 return strings.EqualFold(a.FullName(), b.FullName()) &&
260 normalizeHostname(a.RepoHost()) == normalizeHostname(b.RepoHost())
261}
263type glRepo struct {
264 group string
265 owner string
266 name string
267 fullname string
268 hostname string
269 namespace string
271 project *Project
272}
274type Project struct {
275 *gitlab.Project
276 // for cache invalidation
277 fullname string
278 // for cache invalidation
279 hostname string
280}
282// Project caches the fetched project, so the receiver must be a pointer.
283func (r *glRepo) Project(client *gitlab.Client) (*gitlab.Project, error) {
284 if r.project != nil && r.project.fullname == r.fullname && r.project.hostname == r.hostname {
285 return r.project.Project, nil
286 }
287 p, err := api.GetProject(client, r.fullname)
288 if err != nil {
289 return nil, err
290 }
291 r.project = &Project{
292 Project: p,
293 fullname: r.fullname,
294 hostname: r.hostname,
295 }
296 return r.project.Project, err
297}
299// RepoNamespace returns the namespace of the project. Eg. if project path is :group/:namespace:/repo
300// RepoNamespace returns the :namespace
301func (r glRepo) RepoNamespace() string {
302 return r.namespace
303}
305// RepoGroup returns the group namespace of the project. Eg. if project path is :group/:namespace:/repo
306// RepoGroup returns the :group
307func (r glRepo) RepoGroup() string {
308 return r.group
309}
311// RepoOwner returns the group and namespace in the form "group/namespace". Returns "namespace" if group is not present
312func (r glRepo) RepoOwner() string {
313 if r.group != "" {
314 return r.group + "/" + r.namespace
315 }
316 return r.owner
317}
319// RepoName returns the repo name without the path or namespace.
320func (r glRepo) RepoName() string {
321 return r.name
322}
324// RepoHost returns the hostname
325func (r glRepo) RepoHost() string {
326 return r.hostname
327}
329// FullName returns the full project path :group/:namespace/:repo or :namespace/:repo if group is not present
330func (r glRepo) FullName() string {
331 return r.fullname
332}
Diagnostics6 git calls · 231 ms
CallStatusSizeTime0231 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 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
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=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:0200314 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=222 git.response.bytes=314 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=93a3fb44940eceae81f0a58fd4df1d50fbd7ccb5 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=314 git.pkt.payload.max=287 git.sideband.band1.bytes=287 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=287 git.pack.trailer=0a0d545706824b859dbb83ba13169780ef407392Open pack map
fetch2003.3 KiB222 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=3377 git.response.cache=MISS git.response.duration_ms=222 git.fetch.wants=bb93943644bb31b953863aba38b0f0bea2afe575 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=3377 git.pkt.payload.max=3350 git.sideband.band1.bytes=3350 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
- a5e2d5f1091d689d
- Request
- 528ad0e2…
- 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