Repository navigation
Expand file tree
/
Copy pathgitlab.go
More file actions
683 lines (609 loc) · 19.2 KB
/
Copy pathgitlab.go
File metadata and controls
683 lines (609 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
package gitprovider
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
gitlab "gitlab.com/gitlab-org/api/client-go"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/quartz"
)
type gitlabProvider struct {
webBaseURL string
client *gitlab.Client
clock quartz.Clock
logger slog.Logger
}
func newGitLab(baseURL string, httpClient *http.Client, clock quartz.Clock, logger slog.Logger) (Provider, error) {
if baseURL == "" {
baseURL = "https://gitlab.com"
}
baseURL = strings.TrimRight(baseURL, "/")
baseURL = strings.TrimSuffix(baseURL, "/api/v4")
if httpClient == nil {
httpClient = http.DefaultClient
}
client, err := gitlab.NewClient("",
gitlab.WithBaseURL(baseURL),
gitlab.WithHTTPClient(httpClient),
gitlab.WithoutRetries(),
)
if err != nil {
return nil, xerrors.Errorf("create gitlab client: %w", err)
}
return &gitlabProvider{
webBaseURL: baseURL,
client: client,
clock: clock,
logger: logger,
}, nil
}
var _ Provider = (*gitlabProvider)(nil)
// webHost returns the hostname (with port if present) of the GitLab web URL.
func (g *gitlabProvider) webHost() string {
u, err := url.Parse(g.webBaseURL)
if err != nil {
return "gitlab.com"
}
return u.Host
}
// reqOpts returns per-request options for authentication and context.
func reqOpts(ctx context.Context, token string) []gitlab.RequestOptionFunc {
opts := []gitlab.RequestOptionFunc{gitlab.WithContext(ctx)}
if token != "" {
opts = append(opts, gitlab.WithToken(gitlab.OAuthToken, token))
}
return opts
}
// gitLabPID returns the full project path (owner/repo) for use as a pid.
// The library handles URL encoding internally.
func gitLabPID(owner, repo string) string {
return owner + "/" + repo
}
func (g *gitlabProvider) FetchPullRequestStatus(
ctx context.Context,
token string,
ref PRRef,
) (*PRStatus, error) {
pid := gitLabPID(ref.Owner, ref.Repo)
opts := reqOpts(ctx, token)
// Fetch merge request details.
mr, _, err := g.client.MergeRequests.GetMergeRequest(pid, int64(ref.Number), nil, opts...)
if err != nil {
return nil, g.wrapError(err, "get merge request")
}
// Fetch approvals.
approvals, _, err := g.client.MergeRequests.GetMergeRequestApprovals(pid, int64(ref.Number), opts...)
if err != nil {
return nil, g.wrapError(err, "get merge request approvals")
}
// Fetch commits to get the commit count.
var totalCommits int32
commits, resp, err := g.client.MergeRequests.GetMergeRequestCommits(
pid, int64(ref.Number),
&gitlab.GetMergeRequestCommitsOptions{ListOptions: gitlab.ListOptions{PerPage: 100}},
opts...,
)
if err != nil {
return nil, g.wrapError(err, "get merge request commits")
}
if resp.TotalItems > 0 {
totalCommits = clampToInt32(resp.TotalItems)
} else {
totalCommits = clampToInt32(int64(len(commits)))
}
// Fetch MR diffs to compute additions/deletions.
// The commits endpoint does not return per-commit stats, so we
// count +/- lines from the unified diff returned by this endpoint.
var additions, deletions int32
diffs, _, err := g.client.MergeRequests.ListMergeRequestDiffs(
pid, int64(ref.Number),
// NOTE: fetches a single page of up to 100 diffs. MRs with more than
// 100 changed files will have correct ChangedFiles (from MR metadata)
// but undercounted Additions/Deletions. Pagination is omitted because
// the gitsync worker only uses ChangedFiles for its heuristics today.
&gitlab.ListMergeRequestDiffsOptions{ListOptions: gitlab.ListOptions{PerPage: 100}},
opts...,
)
if err != nil {
return nil, g.wrapError(err, "list merge request diffs")
}
for _, d := range diffs {
diffAdditions, diffDeletions := countDiffLines(d.Diff)
additions += diffAdditions
deletions += diffDeletions
}
// Map GitLab state to normalized state.
state := mapGitLabState(mr.State)
// Use diff_refs.head_sha if available, fall back to top-level sha.
headSHA := cmp.Or(mr.DiffRefs.HeadSha, mr.SHA)
// Parse changes_count (it's a string, possibly "1000+").
var changedFiles int32
if mr.ChangesCount != "" {
trimmed := strings.TrimSuffix(mr.ChangesCount, "+")
if n, err := strconv.ParseInt(trimmed, 10, 32); err == nil {
changedFiles = int32(n)
}
}
// TODO(CODAGT-440): These fields have semantic gaps vs the GitHub
// provider. GitLab's "Approved" is threshold-based (not "at least one
// approval and no changes requested"), ChangesRequested has no GitLab
// equivalent, and ReviewerCount only counts approvers.
reviewerCount := clampToInt32(int64(len(approvals.ApprovedBy)))
var authorLogin, authorAvatarURL string
if mr.Author != nil {
authorLogin = mr.Author.Username
authorAvatarURL = mr.Author.AvatarURL
}
return &PRStatus{
Title: mr.Title,
State: state,
Draft: mr.Draft,
HeadSHA: headSHA,
HeadBranch: mr.SourceBranch,
DiffStats: DiffStats{
Additions: additions,
Deletions: deletions,
ChangedFiles: changedFiles,
},
ChangesRequested: false,
Approved: approvals.Approved,
ReviewerCount: reviewerCount,
AuthorLogin: authorLogin,
AuthorAvatarURL: authorAvatarURL,
BaseBranch: mr.TargetBranch,
PRNumber: int(mr.IID),
Commits: totalCommits,
FetchedAt: g.clock.Now().UTC(),
}, nil
}
func (g *gitlabProvider) ResolveBranchPullRequest(
ctx context.Context,
token string,
ref BranchRef,
) (*PRRef, error) {
if ref.Owner == "" || ref.Repo == "" || ref.Branch == "" {
return nil, nil //nolint:nilnil // Provider contract: nil, nil means no open PR.
}
pid := gitLabPID(ref.Owner, ref.Repo)
opts := reqOpts(ctx, token)
mrs, _, err := g.client.MergeRequests.ListProjectMergeRequests(pid, &gitlab.ListProjectMergeRequestsOptions{
ListOptions: gitlab.ListOptions{PerPage: 1},
SourceBranch: gitlab.Ptr(ref.Branch),
State: gitlab.Ptr("opened"),
OrderBy: gitlab.Ptr("updated_at"),
Sort: gitlab.Ptr("desc"),
}, opts...)
if err != nil {
return nil, g.wrapError(err, "list merge requests by branch")
}
if len(mrs) == 0 {
return nil, nil //nolint:nilnil // Provider contract: nil, nil means no open PR.
}
prRef, ok := g.ParsePullRequestURL(mrs[0].WebURL)
if !ok {
// Fallback: construct from known owner/repo and returned IID.
return &PRRef{
Owner: ref.Owner,
Repo: ref.Repo,
Number: int(mrs[0].IID),
}, nil
}
return &prRef, nil
}
func (g *gitlabProvider) FetchPullRequestDiff(
ctx context.Context,
token string,
ref PRRef,
) (string, error) {
pid := gitLabPID(ref.Owner, ref.Repo)
// Make a direct HTTP request instead of using the library's
// ShowMergeRequestRawDiffs, which reads the entire response
// into memory before returning. We use io.LimitReader to
// bound memory and reject diffs exceeding MaxDiffSize.
rawURL := fmt.Sprintf("%sprojects/%s/merge_requests/%d/raw_diffs",
g.client.BaseURL().String(), url.PathEscape(pid), ref.Number)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return "", g.wrapError(err, "create raw diffs request")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := g.client.HTTPClient().Do(req)
if err != nil {
return "", g.wrapError(err, "get merge request raw diffs")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if rlErr := checkRateLimitError(resp, g.clock, "RateLimit-Reset"); rlErr != nil {
return "", rlErr
}
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 8192))
if readErr != nil {
return "", g.wrapError(
xerrors.Errorf("unexpected status %d", resp.StatusCode),
"get merge request raw diffs",
)
}
return "", g.wrapError(
xerrors.Errorf("unexpected status %d: %s", resp.StatusCode, strings.TrimSpace(string(body))),
"get merge request raw diffs",
)
}
buf, err := io.ReadAll(io.LimitReader(resp.Body, MaxDiffSize+1))
if err != nil {
return "", g.wrapError(err, "read merge request raw diffs")
}
if len(buf) > MaxDiffSize {
return "", ErrDiffTooLarge
}
return string(buf), nil
}
// compareResponse is the subset of GitLab's compare endpoint response
// that we need. We decode manually (instead of using the library) so
// we can bound memory with io.LimitReader before JSON parsing.
type compareResponse struct {
Diffs []struct {
Diff string `json:"diff"`
OldPath string `json:"old_path"`
NewPath string `json:"new_path"`
NewFile bool `json:"new_file"`
DeletedFile bool `json:"deleted_file"`
RenamedFile bool `json:"renamed_file"`
Collapsed bool `json:"collapsed"`
TooLarge bool `json:"too_large"`
} `json:"diffs"`
CompareTimeout bool `json:"compare_timeout"`
}
func (g *gitlabProvider) FetchBranchDiff(
ctx context.Context,
token string,
ref BranchRef,
) (string, error) {
if ref.Owner == "" || ref.Repo == "" || ref.Branch == "" {
return "", nil
}
pid := gitLabPID(ref.Owner, ref.Repo)
opts := reqOpts(ctx, token)
// Get the default branch from the project.
project, _, err := g.client.Projects.GetProject(pid, nil, opts...)
if err != nil {
return "", g.wrapError(err, "get project")
}
defaultBranch := strings.TrimSpace(project.DefaultBranch)
if defaultBranch == "" {
return "", xerrors.New("gitlab project default branch is empty")
}
// Use raw HTTP with io.LimitReader to bound memory. The library's
// Compare() decodes the full response before returning, which
// would allow a maliciously large diff to OOM the process.
compareURL := fmt.Sprintf("%sprojects/%s/repository/compare?from=%s&to=%s&unidiff=true",
g.client.BaseURL().String(),
url.PathEscape(pid),
url.QueryEscape(defaultBranch),
url.QueryEscape(ref.Branch),
)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, compareURL, nil)
if err != nil {
return "", g.wrapError(err, "create compare request")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := g.client.HTTPClient().Do(req)
if err != nil {
return "", g.wrapError(err, "compare branches")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if rlErr := checkRateLimitError(resp, g.clock, "RateLimit-Reset"); rlErr != nil {
return "", rlErr
}
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 8192))
if readErr != nil {
return "", g.wrapError(
xerrors.Errorf("unexpected status %d", resp.StatusCode),
"compare branches",
)
}
return "", g.wrapError(
xerrors.Errorf("unexpected status %d: %s", resp.StatusCode, strings.TrimSpace(string(body))),
"compare branches",
)
}
// Bound the read to MaxDiffSize + overhead for JSON structure.
// The JSON envelope (commits, metadata) adds some overhead beyond
// the raw diff content, so we allow ~10% extra for framing.
maxRead := int64(MaxDiffSize) + int64(MaxDiffSize/10) + 4096
body, err := io.ReadAll(io.LimitReader(resp.Body, maxRead+1))
if err != nil {
return "", g.wrapError(err, "read compare response")
}
if int64(len(body)) > maxRead {
return "", ErrDiffTooLarge
}
var compare compareResponse
if err := json.Unmarshal(body, &compare); err != nil {
return "", g.wrapError(err, "decode compare response")
}
if compare.CompareTimeout {
return "", xerrors.New("gitlab compare timed out; diff may be incomplete")
}
// Reconstruct unified diff from individual file diffs.
var sb strings.Builder
var estimated int
for _, d := range compare.Diffs {
estimated += len(d.Diff) + len(d.OldPath) + len(d.NewPath) + 20
}
if estimated > MaxDiffSize {
return "", ErrDiffTooLarge
}
sb.Grow(estimated)
for _, d := range compare.Diffs {
if d.Collapsed || d.TooLarge {
g.logger.Warn(ctx, "gitlab compare: file diff truncated",
slog.F("path", d.NewPath),
slog.F("collapsed", d.Collapsed),
slog.F("too_large", d.TooLarge),
)
}
_, _ = fmt.Fprintf(&sb, "diff --git a/%s b/%s\n", d.OldPath, d.NewPath)
// Add standard unified diff file headers.
switch {
case d.NewFile:
_, _ = sb.WriteString("--- /dev/null\n")
_, _ = fmt.Fprintf(&sb, "+++ b/%s\n", d.NewPath)
case d.DeletedFile:
_, _ = fmt.Fprintf(&sb, "--- a/%s\n", d.OldPath)
_, _ = sb.WriteString("+++ /dev/null\n")
default:
_, _ = fmt.Fprintf(&sb, "--- a/%s\n", d.OldPath)
_, _ = fmt.Fprintf(&sb, "+++ b/%s\n", d.NewPath)
}
_, _ = sb.WriteString(d.Diff)
// Ensure each file diff ends with a newline.
if len(d.Diff) > 0 && d.Diff[len(d.Diff)-1] != '\n' {
_ = sb.WriteByte('\n')
}
}
result := sb.String()
if len(result) > MaxDiffSize {
return "", ErrDiffTooLarge
}
return result, nil
}
// ParseRepositoryOrigin preserves slashes in owner because GitLab supports
// subgroup paths such as group/subgroup/repo.
//
// TODO: this does not handle GitLab instances installed under a relative URL
// prefix (e.g. https://example.com/gitlab/). See
// https://docs.gitlab.com/install/relative_url/ for details.
func (g *gitlabProvider) ParseRepositoryOrigin(raw string) (owner, repo, normalizedOrigin string, ok bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", "", "", false
}
host := g.webHost()
// Try SSH format: git@HOST:path.git or ssh://git@HOST/path.git
if path, matched := parseSSHOrigin(raw, host); matched {
owner, repo = splitOwnerRepo(path)
if owner == "" || repo == "" {
return "", "", "", false
}
normalized := fmt.Sprintf("%s/%s/%s", g.webBaseURL, owner, repo)
return owner, repo, normalized, true
}
// Try HTTPS format.
u, err := url.Parse(raw)
if err != nil {
return "", "", "", false
}
if !strings.EqualFold(u.Host, host) {
return "", "", "", false
}
if u.Scheme != "https" && u.Scheme != "http" {
return "", "", "", false
}
path := strings.TrimPrefix(u.Path, "/")
path = strings.TrimSuffix(path, "/")
path = strings.TrimSuffix(path, ".git")
if path == "" {
return "", "", "", false
}
owner, repo = splitOwnerRepo(path)
if owner == "" || repo == "" {
return "", "", "", false
}
normalized := fmt.Sprintf("%s/%s/%s", g.webBaseURL, owner, repo)
return owner, repo, normalized, true
}
func (g *gitlabProvider) ParsePullRequestURL(raw string) (PRRef, bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return PRRef{}, false
}
u, err := url.Parse(raw)
if err != nil {
return PRRef{}, false
}
host := g.webHost()
if !strings.EqualFold(u.Host, host) {
return PRRef{}, false
}
// GitLab MR URLs: /owner/repo/-/merge_requests/123
// or /group/subgroup/repo/-/merge_requests/123
path := strings.TrimPrefix(u.Path, "/")
path = strings.TrimSuffix(path, "/")
// Find "-/merge_requests/NUMBER" in the path.
const mrMarker = "-/merge_requests/"
idx := strings.Index(path, mrMarker)
if idx < 0 {
return PRRef{}, false
}
// Everything before the marker (minus trailing slash) is the project path.
projPath := path[:idx]
projPath = strings.TrimSuffix(projPath, "/")
if projPath == "" {
return PRRef{}, false
}
// The number comes after the marker.
afterMR := path[idx+len(mrMarker):]
// Strip any trailing path segments.
if slashIdx := strings.Index(afterMR, "/"); slashIdx >= 0 {
afterMR = afterMR[:slashIdx]
}
number, err := strconv.Atoi(afterMR)
if err != nil || number <= 0 {
return PRRef{}, false
}
owner, repo := splitOwnerRepo(projPath)
if owner == "" || repo == "" {
return PRRef{}, false
}
return PRRef{
Owner: owner,
Repo: repo,
Number: number,
}, true
}
// NormalizePullRequestURL normalizes a GitLab merge request URL.
func (g *gitlabProvider) NormalizePullRequestURL(raw string) string {
ref, ok := g.ParsePullRequestURL(strings.TrimRight(
strings.TrimSpace(raw),
trailingPunctuation,
))
if !ok {
return ""
}
return g.BuildPullRequestURL(ref)
}
// BuildBranchURL keeps owner and repo unescaped because GitLab owners can
// include subgroup paths with slashes.
func (g *gitlabProvider) BuildBranchURL(owner, repo, branch string) string {
owner = strings.TrimSpace(owner)
repo = strings.TrimSpace(repo)
branch = strings.TrimSpace(branch)
if owner == "" || repo == "" || branch == "" {
return ""
}
return fmt.Sprintf(
"%s/%s/%s/-/tree/%s",
g.webBaseURL,
owner,
repo,
escapePathPreserveSlashes(branch),
)
}
// BuildRepositoryURL keeps owner and repo unescaped because GitLab owners can
// include subgroup paths with slashes.
func (g *gitlabProvider) BuildRepositoryURL(owner, repo string) string {
owner = strings.TrimSpace(owner)
repo = strings.TrimSpace(repo)
if owner == "" || repo == "" {
return ""
}
return fmt.Sprintf("%s/%s/%s", g.webBaseURL, owner, repo)
}
func (g *gitlabProvider) BuildPullRequestURL(ref PRRef) string {
if ref.Owner == "" || ref.Repo == "" || ref.Number <= 0 {
return ""
}
return fmt.Sprintf("%s/%s/%s/-/merge_requests/%d", g.webBaseURL, ref.Owner, ref.Repo, ref.Number)
}
// wrapError converts library errors to our domain errors (e.g. rate limits).
func (g *gitlabProvider) wrapError(err error, action string) error {
if errResp, ok := errors.AsType[*gitlab.ErrorResponse](err); ok {
if rlErr := checkRateLimitError(errResp.Response, g.clock, "RateLimit-Reset"); rlErr != nil {
return rlErr
}
}
return xerrors.Errorf("gitlab %s: %w", action, err)
}
// mapGitLabState maps a GitLab merge request state string to a normalized PRState.
func mapGitLabState(state string) PRState {
switch strings.ToLower(strings.TrimSpace(state)) {
case "opened":
return PRStateOpen
case "merged":
return PRStateMerged
case "closed", "locked":
return PRStateClosed
default:
return PRStateClosed
}
}
// splitOwnerRepo splits a path like "group/subgroup/repo" into
// owner="group/subgroup" and repo="repo". The last segment is always
// the repo name, and everything before it is the owner.
func splitOwnerRepo(path string) (owner, repo string) {
path = strings.TrimPrefix(path, "/")
path = strings.TrimSuffix(path, "/")
if path == "" {
return "", ""
}
lastSlash := strings.LastIndex(path, "/")
if lastSlash < 0 {
// No slash means no owner/repo split possible.
return "", ""
}
owner = path[:lastSlash]
repo = path[lastSlash+1:]
if owner == "" || repo == "" {
return "", ""
}
return owner, repo
}
// parseSSHOrigin attempts to parse an SSH git remote URL for the given host.
// Returns the path (without .git suffix) and true if it matched.
func parseSSHOrigin(raw string, host string) (string, bool) {
// Handle ssh://git@HOST/path.git format.
if strings.HasPrefix(raw, "ssh://") {
u, err := url.Parse(raw)
if err != nil {
return "", false
}
// The host in SSH URLs may include a port, so compare case-insensitively.
if !strings.EqualFold(u.Host, host) && !strings.EqualFold(u.Hostname(), hostWithoutPort(host)) {
return "", false
}
path := strings.TrimPrefix(u.Path, "/")
path = strings.TrimSuffix(path, ".git")
path = strings.TrimSuffix(path, "/")
if path == "" {
return "", false
}
return path, true
}
// Handle git@HOST:path.git format (SCP-like syntax).
prefix := "git@" + host + ":"
// Also try matching without port for host comparison.
prefixNoPort := "git@" + hostWithoutPort(host) + ":"
path, ok := strings.CutPrefix(raw, prefix)
if !ok {
path, ok = strings.CutPrefix(raw, prefixNoPort)
}
if !ok {
return "", false
}
path = strings.TrimSuffix(path, ".git")
path = strings.TrimSuffix(path, "/")
if path == "" {
return "", false
}
return path, true
}
// hostWithoutPort strips the port from a host:port string.
func hostWithoutPort(host string) string {
if idx := strings.LastIndex(host, ":"); idx >= 0 {
return host[:idx]
}
return host
}