1
2
3
4
5 package vcs
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "internal/godebug"
12 "internal/lazyregexp"
13 "internal/singleflight"
14 "io/fs"
15 "log"
16 urlpkg "net/url"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "strconv"
21 "strings"
22 "sync"
23 "time"
24
25 "cmd/go/internal/base"
26 "cmd/go/internal/cfg"
27 "cmd/go/internal/search"
28 "cmd/go/internal/str"
29 "cmd/go/internal/web"
30 "cmd/internal/pathcache"
31
32 "golang.org/x/mod/module"
33 )
34
35
36
37 type Cmd struct {
38 Name string
39 Cmd string
40 Env []string
41 RootNames []rootName
42
43 Scheme []string
44 PingCmd string
45
46 Status func(v *Cmd, rootDir string) (Status, error)
47 }
48
49
50 type Status struct {
51 Revision string
52 CommitTime time.Time
53 Uncommitted bool
54 }
55
56 var (
57
58
59
60
61
62 VCSTestRepoURL string
63
64
65 VCSTestHosts []string
66
67
68
69 VCSTestIsLocalHost func(*urlpkg.URL) bool
70 )
71
72 var defaultSecureScheme = map[string]bool{
73 "https": true,
74 "git+ssh": true,
75 "bzr+ssh": true,
76 "svn+ssh": true,
77 "ssh": true,
78 }
79
80 func (v *Cmd) IsSecure(repo string) bool {
81 u, err := urlpkg.Parse(repo)
82 if err != nil {
83
84 return false
85 }
86 if VCSTestRepoURL != "" && web.IsLocalHost(u) {
87
88
89
90 return true
91 }
92 return v.isSecureScheme(u.Scheme)
93 }
94
95 func (v *Cmd) isSecureScheme(scheme string) bool {
96 switch v.Cmd {
97 case "git":
98
99
100
101 if allow := os.Getenv("GIT_ALLOW_PROTOCOL"); allow != "" {
102 for _, s := range strings.Split(allow, ":") {
103 if s == scheme {
104 return true
105 }
106 }
107 return false
108 }
109 }
110 return defaultSecureScheme[scheme]
111 }
112
113
114
115 type tagCmd struct {
116 cmd string
117 pattern string
118 }
119
120
121 var vcsList = []*Cmd{
122 vcsHg,
123 vcsGit,
124 vcsSvn,
125 vcsBzr,
126 vcsFossil,
127 }
128
129
130
131 var vcsMod = &Cmd{Name: "mod"}
132
133
134
135 func vcsByCmd(cmd string) *Cmd {
136 for _, vcs := range vcsList {
137 if vcs.Cmd == cmd {
138 return vcs
139 }
140 }
141 return nil
142 }
143
144
145 var vcsHg = &Cmd{
146 Name: "Mercurial",
147 Cmd: "hg",
148
149
150
151 Env: []string{"HGPLAIN=+strictflags"},
152 RootNames: []rootName{
153 {filename: ".hg", isDir: true},
154 },
155
156 Scheme: []string{"https", "http", "ssh"},
157 PingCmd: "identify -- {scheme}://{repo}",
158 Status: hgStatus,
159 }
160
161 func hgStatus(vcsHg *Cmd, rootDir string) (Status, error) {
162
163 out, err := vcsHg.runOutputVerboseOnly(rootDir, `log -r. -T {node}:{date|hgdate}`)
164 if err != nil {
165 return Status{}, err
166 }
167
168 var rev string
169 var commitTime time.Time
170 if len(out) > 0 {
171
172 if i := bytes.IndexByte(out, ' '); i > 0 {
173 out = out[:i]
174 }
175 rev, commitTime, err = parseRevTime(out)
176 if err != nil {
177 return Status{}, err
178 }
179 }
180
181
182 out, err = vcsHg.runOutputVerboseOnly(rootDir, "status -S")
183 if err != nil {
184 return Status{}, err
185 }
186 uncommitted := len(out) > 0
187
188 return Status{
189 Revision: rev,
190 CommitTime: commitTime,
191 Uncommitted: uncommitted,
192 }, nil
193 }
194
195
196 func parseRevTime(out []byte) (string, time.Time, error) {
197 buf := string(bytes.TrimSpace(out))
198
199 i := strings.IndexByte(buf, ':')
200 if i < 1 {
201 return "", time.Time{}, errors.New("unrecognized VCS tool output")
202 }
203 rev := buf[:i]
204
205 secs, err := strconv.ParseInt(string(buf[i+1:]), 10, 64)
206 if err != nil {
207 return "", time.Time{}, fmt.Errorf("unrecognized VCS tool output: %v", err)
208 }
209
210 return rev, time.Unix(secs, 0), nil
211 }
212
213
214 var vcsGit = &Cmd{
215 Name: "Git",
216 Cmd: "git",
217 RootNames: []rootName{
218 {filename: ".git", isDir: true},
219 },
220
221 Scheme: []string{"git", "https", "http", "git+ssh", "ssh"},
222
223
224
225
226
227 PingCmd: "ls-remote {scheme}://{repo}",
228
229 Status: gitStatus,
230 }
231
232 func gitStatus(vcsGit *Cmd, rootDir string) (Status, error) {
233 out, err := vcsGit.runOutputVerboseOnly(rootDir, "status --porcelain")
234 if err != nil {
235 return Status{}, err
236 }
237 uncommitted := len(out) > 0
238
239
240
241
242 var rev string
243 var commitTime time.Time
244 out, err = vcsGit.runOutputVerboseOnly(rootDir, "-c log.showsignature=false log -1 --format=%H:%ct")
245 if err != nil && !uncommitted {
246 return Status{}, err
247 } else if err == nil {
248 rev, commitTime, err = parseRevTime(out)
249 if err != nil {
250 return Status{}, err
251 }
252 }
253
254 return Status{
255 Revision: rev,
256 CommitTime: commitTime,
257 Uncommitted: uncommitted,
258 }, nil
259 }
260
261
262 var vcsBzr = &Cmd{
263 Name: "Bazaar",
264 Cmd: "bzr",
265 RootNames: []rootName{
266 {filename: ".bzr", isDir: true},
267 },
268
269 Scheme: []string{"https", "http", "bzr", "bzr+ssh"},
270 PingCmd: "info -- {scheme}://{repo}",
271 Status: bzrStatus,
272 }
273
274 func bzrStatus(vcsBzr *Cmd, rootDir string) (Status, error) {
275 outb, err := vcsBzr.runOutputVerboseOnly(rootDir, "version-info")
276 if err != nil {
277 return Status{}, err
278 }
279 out := string(outb)
280
281
282
283
284
285
286 var rev string
287 var commitTime time.Time
288
289 for _, line := range strings.Split(out, "\n") {
290 i := strings.IndexByte(line, ':')
291 if i < 0 {
292 continue
293 }
294 key := line[:i]
295 value := strings.TrimSpace(line[i+1:])
296
297 switch key {
298 case "revision-id":
299 rev = value
300 case "date":
301 var err error
302 commitTime, err = time.Parse("2006-01-02 15:04:05 -0700", value)
303 if err != nil {
304 return Status{}, errors.New("unable to parse output of bzr version-info")
305 }
306 }
307 }
308
309 outb, err = vcsBzr.runOutputVerboseOnly(rootDir, "status")
310 if err != nil {
311 return Status{}, err
312 }
313
314
315 if bytes.HasPrefix(outb, []byte("working tree is out of date")) {
316 i := bytes.IndexByte(outb, '\n')
317 if i < 0 {
318 i = len(outb)
319 }
320 outb = outb[:i]
321 }
322 uncommitted := len(outb) > 0
323
324 return Status{
325 Revision: rev,
326 CommitTime: commitTime,
327 Uncommitted: uncommitted,
328 }, nil
329 }
330
331
332 var vcsSvn = &Cmd{
333 Name: "Subversion",
334 Cmd: "svn",
335 RootNames: []rootName{
336 {filename: ".svn", isDir: true},
337 },
338
339
340
341
342 Scheme: []string{"https", "http", "svn", "svn+ssh"},
343 PingCmd: "info -- {scheme}://{repo}",
344 Status: svnStatus,
345 }
346
347 func svnStatus(vcsSvn *Cmd, rootDir string) (Status, error) {
348 out, err := vcsSvn.runOutputVerboseOnly(rootDir, "info --show-item last-changed-revision")
349 if err != nil {
350 return Status{}, err
351 }
352 rev := strings.TrimSpace(string(out))
353
354 out, err = vcsSvn.runOutputVerboseOnly(rootDir, "info --show-item last-changed-date")
355 if err != nil {
356 return Status{}, err
357 }
358 commitTime, err := time.Parse(time.RFC3339, strings.TrimSpace(string(out)))
359 if err != nil {
360 return Status{}, fmt.Errorf("unable to parse output of svn info: %v", err)
361 }
362
363 out, err = vcsSvn.runOutputVerboseOnly(rootDir, "status")
364 if err != nil {
365 return Status{}, err
366 }
367 uncommitted := len(out) > 0
368
369 return Status{
370 Revision: rev,
371 CommitTime: commitTime,
372 Uncommitted: uncommitted,
373 }, nil
374 }
375
376
377
378 const fossilRepoName = ".fossil"
379
380
381 var vcsFossil = &Cmd{
382 Name: "Fossil",
383 Cmd: "fossil",
384 RootNames: []rootName{
385 {filename: ".fslckout", isDir: false},
386 {filename: "_FOSSIL_", isDir: false},
387 },
388
389 Scheme: []string{"https", "http"},
390 Status: fossilStatus,
391 }
392
393 var errFossilInfo = errors.New("unable to parse output of fossil info")
394
395 func fossilStatus(vcsFossil *Cmd, rootDir string) (Status, error) {
396 outb, err := vcsFossil.runOutputVerboseOnly(rootDir, "info")
397 if err != nil {
398 return Status{}, err
399 }
400 out := string(outb)
401
402
403
404
405
406
407
408
409 const prefix = "\ncheckout:"
410 const suffix = " UTC"
411 i := strings.Index(out, prefix)
412 if i < 0 {
413 return Status{}, errFossilInfo
414 }
415 checkout := out[i+len(prefix):]
416 i = strings.Index(checkout, suffix)
417 if i < 0 {
418 return Status{}, errFossilInfo
419 }
420 checkout = strings.TrimSpace(checkout[:i])
421
422 i = strings.IndexByte(checkout, ' ')
423 if i < 0 {
424 return Status{}, errFossilInfo
425 }
426 rev := checkout[:i]
427
428 commitTime, err := time.ParseInLocation(time.DateTime, checkout[i+1:], time.UTC)
429 if err != nil {
430 return Status{}, fmt.Errorf("%v: %v", errFossilInfo, err)
431 }
432
433
434 outb, err = vcsFossil.runOutputVerboseOnly(rootDir, "changes --differ")
435 if err != nil {
436 return Status{}, err
437 }
438 uncommitted := len(outb) > 0
439
440 return Status{
441 Revision: rev,
442 CommitTime: commitTime,
443 Uncommitted: uncommitted,
444 }, nil
445 }
446
447 func (v *Cmd) String() string {
448 return v.Name
449 }
450
451
452
453
454
455
456
457
458 func (v *Cmd) run(dir string, cmd string, keyval ...string) error {
459 _, err := v.run1(dir, cmd, keyval, true)
460 return err
461 }
462
463
464 func (v *Cmd) runVerboseOnly(dir string, cmd string, keyval ...string) error {
465 _, err := v.run1(dir, cmd, keyval, false)
466 return err
467 }
468
469
470 func (v *Cmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {
471 return v.run1(dir, cmd, keyval, true)
472 }
473
474
475
476 func (v *Cmd) runOutputVerboseOnly(dir string, cmd string, keyval ...string) ([]byte, error) {
477 return v.run1(dir, cmd, keyval, false)
478 }
479
480
481 func (v *Cmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([]byte, error) {
482 m := make(map[string]string)
483 for i := 0; i < len(keyval); i += 2 {
484 m[keyval[i]] = keyval[i+1]
485 }
486 args := strings.Fields(cmdline)
487 for i, arg := range args {
488 args[i] = expand(m, arg)
489 }
490
491 if len(args) >= 2 && args[0] == "--go-internal-mkdir" {
492 var err error
493 if filepath.IsAbs(args[1]) {
494 err = os.Mkdir(args[1], fs.ModePerm)
495 } else {
496 err = os.Mkdir(filepath.Join(dir, args[1]), fs.ModePerm)
497 }
498 if err != nil {
499 return nil, err
500 }
501 args = args[2:]
502 }
503
504 if len(args) >= 2 && args[0] == "--go-internal-cd" {
505 if filepath.IsAbs(args[1]) {
506 dir = args[1]
507 } else {
508 dir = filepath.Join(dir, args[1])
509 }
510 args = args[2:]
511 }
512
513 _, err := pathcache.LookPath(v.Cmd)
514 if err != nil {
515 fmt.Fprintf(os.Stderr,
516 "go: missing %s command. See https://golang.org/s/gogetcmd\n",
517 v.Name)
518 return nil, err
519 }
520
521 cmd := exec.Command(v.Cmd, args...)
522 cmd.Dir = dir
523 if v.Env != nil {
524 cmd.Env = append(cmd.Environ(), v.Env...)
525 }
526 if cfg.BuildX {
527 fmt.Fprintf(os.Stderr, "cd %s\n", dir)
528 fmt.Fprintf(os.Stderr, "%s %s\n", v.Cmd, strings.Join(args, " "))
529 }
530 out, err := cmd.Output()
531 if err != nil {
532 if verbose || cfg.BuildV {
533 fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.Cmd, strings.Join(args, " "))
534 if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
535 os.Stderr.Write(ee.Stderr)
536 } else {
537 fmt.Fprintln(os.Stderr, err.Error())
538 }
539 }
540 }
541 return out, err
542 }
543
544
545 func (v *Cmd) Ping(scheme, repo string) error {
546
547
548
549
550 dir := cfg.GOMODCACHE
551 if !cfg.ModulesEnabled {
552 dir = filepath.Join(cfg.BuildContext.GOPATH, "src")
553 }
554 os.MkdirAll(dir, 0777)
555
556 release, err := base.AcquireNet()
557 if err != nil {
558 return err
559 }
560 defer release()
561
562 return v.runVerboseOnly(dir, v.PingCmd, "scheme", scheme, "repo", repo)
563 }
564
565
566
567 type vcsPath struct {
568 pathPrefix string
569 regexp *lazyregexp.Regexp
570 repo string
571 vcs string
572 check func(match map[string]string) error
573 schemelessRepo bool
574 }
575
576 var allowmultiplevcs = godebug.New("allowmultiplevcs")
577
578
579
580
581
582 func FromDir(dir, srcRoot string) (repoDir string, vcsCmd *Cmd, err error) {
583
584 dir = filepath.Clean(dir)
585 if srcRoot != "" {
586 srcRoot = filepath.Clean(srcRoot)
587 if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator {
588 return "", nil, fmt.Errorf("directory %q is outside source root %q", dir, srcRoot)
589 }
590 }
591
592 origDir := dir
593 for len(dir) > len(srcRoot) {
594 for _, vcs := range vcsList {
595 if isVCSRoot(dir, vcs.RootNames) {
596 if vcsCmd == nil {
597
598 vcsCmd = vcs
599 repoDir = dir
600 if allowmultiplevcs.Value() == "1" {
601 allowmultiplevcs.IncNonDefault()
602 return repoDir, vcsCmd, nil
603 }
604
605
606
607
608 continue
609 }
610 if vcsCmd == vcsGit && vcs == vcsGit {
611
612
613
614 continue
615 }
616 return "", nil, fmt.Errorf("multiple VCS detected: %s in %q, and %s in %q",
617 vcsCmd.Cmd, repoDir, vcs.Cmd, dir)
618 }
619 }
620
621
622 ndir := filepath.Dir(dir)
623 if len(ndir) >= len(dir) {
624 break
625 }
626 dir = ndir
627 }
628 if vcsCmd == nil {
629 return "", nil, &vcsNotFoundError{dir: origDir}
630 }
631 return repoDir, vcsCmd, nil
632 }
633
634
635
636 func isVCSRoot(dir string, rootNames []rootName) bool {
637 for _, root := range rootNames {
638 fi, err := os.Stat(filepath.Join(dir, root.filename))
639 if err == nil && fi.IsDir() == root.isDir {
640 return true
641 }
642 }
643
644 return false
645 }
646
647 type rootName struct {
648 filename string
649 isDir bool
650 }
651
652 type vcsNotFoundError struct {
653 dir string
654 }
655
656 func (e *vcsNotFoundError) Error() string {
657 return fmt.Sprintf("directory %q is not using a known version control system", e.dir)
658 }
659
660 func (e *vcsNotFoundError) Is(err error) bool {
661 return err == os.ErrNotExist
662 }
663
664
665 type govcsRule struct {
666 pattern string
667 allowed []string
668 }
669
670
671 type govcsConfig []govcsRule
672
673 func parseGOVCS(s string) (govcsConfig, error) {
674 s = strings.TrimSpace(s)
675 if s == "" {
676 return nil, nil
677 }
678 var cfg govcsConfig
679 have := make(map[string]string)
680 for _, item := range strings.Split(s, ",") {
681 item = strings.TrimSpace(item)
682 if item == "" {
683 return nil, fmt.Errorf("empty entry in GOVCS")
684 }
685 pattern, list, found := strings.Cut(item, ":")
686 if !found {
687 return nil, fmt.Errorf("malformed entry in GOVCS (missing colon): %q", item)
688 }
689 pattern, list = strings.TrimSpace(pattern), strings.TrimSpace(list)
690 if pattern == "" {
691 return nil, fmt.Errorf("empty pattern in GOVCS: %q", item)
692 }
693 if list == "" {
694 return nil, fmt.Errorf("empty VCS list in GOVCS: %q", item)
695 }
696 if search.IsRelativePath(pattern) {
697 return nil, fmt.Errorf("relative pattern not allowed in GOVCS: %q", pattern)
698 }
699 if old := have[pattern]; old != "" {
700 return nil, fmt.Errorf("unreachable pattern in GOVCS: %q after %q", item, old)
701 }
702 have[pattern] = item
703 allowed := strings.Split(list, "|")
704 for i, a := range allowed {
705 a = strings.TrimSpace(a)
706 if a == "" {
707 return nil, fmt.Errorf("empty VCS name in GOVCS: %q", item)
708 }
709 allowed[i] = a
710 }
711 cfg = append(cfg, govcsRule{pattern, allowed})
712 }
713 return cfg, nil
714 }
715
716 func (c *govcsConfig) allow(path string, private bool, vcs string) bool {
717 for _, rule := range *c {
718 match := false
719 switch rule.pattern {
720 case "private":
721 match = private
722 case "public":
723 match = !private
724 default:
725
726
727 match = module.MatchPrefixPatterns(rule.pattern, path)
728 }
729 if !match {
730 continue
731 }
732 for _, allow := range rule.allowed {
733 if allow == vcs || allow == "all" {
734 return true
735 }
736 }
737 return false
738 }
739
740
741 return false
742 }
743
744 var (
745 govcs govcsConfig
746 govcsErr error
747 govcsOnce sync.Once
748 )
749
750
751
752
753
754
755
756
757
758
759
760
761
762 var defaultGOVCS = govcsConfig{
763 {"private", []string{"all"}},
764 {"public", []string{"git", "hg"}},
765 }
766
767
768
769
770
771 func checkGOVCS(vcs *Cmd, root string) error {
772 if vcs == vcsMod {
773
774
775
776 return nil
777 }
778
779 govcsOnce.Do(func() {
780 govcs, govcsErr = parseGOVCS(os.Getenv("GOVCS"))
781 govcs = append(govcs, defaultGOVCS...)
782 })
783 if govcsErr != nil {
784 return govcsErr
785 }
786
787 private := module.MatchPrefixPatterns(cfg.GOPRIVATE, root)
788 if !govcs.allow(root, private, vcs.Cmd) {
789 what := "public"
790 if private {
791 what = "private"
792 }
793 return fmt.Errorf("GOVCS disallows using %s for %s %s; see 'go help vcs'", vcs.Cmd, what, root)
794 }
795
796 return nil
797 }
798
799
800 type RepoRoot struct {
801 Repo string
802 Root string
803 SubDir string
804 IsCustom bool
805 VCS *Cmd
806 }
807
808 func httpPrefix(s string) string {
809 for _, prefix := range [...]string{"http:", "https:"} {
810 if strings.HasPrefix(s, prefix) {
811 return prefix
812 }
813 }
814 return ""
815 }
816
817
818 type ModuleMode int
819
820 const (
821 IgnoreMod ModuleMode = iota
822 PreferMod
823 )
824
825
826
827 func RepoRootForImportPath(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
828 rr, err := repoRootFromVCSPaths(importPath, security, vcsPaths)
829 if err == errUnknownSite {
830 rr, err = repoRootForImportDynamic(importPath, mod, security)
831 if err != nil {
832 err = importErrorf(importPath, "unrecognized import path %q: %v", importPath, err)
833 }
834 }
835 if err != nil {
836 rr1, err1 := repoRootFromVCSPaths(importPath, security, vcsPathsAfterDynamic)
837 if err1 == nil {
838 rr = rr1
839 err = nil
840 }
841 }
842
843
844 if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.Root, "...") {
845
846 rr = nil
847 err = importErrorf(importPath, "cannot expand ... in %q", importPath)
848 }
849 return rr, err
850 }
851
852 var errUnknownSite = errors.New("dynamic lookup required to find mapping")
853
854
855
856 func repoRootFromVCSPaths(importPath string, security web.SecurityMode, vcsPaths []*vcsPath) (*RepoRoot, error) {
857 if str.HasPathPrefix(importPath, "example.net") {
858
859
860
861
862 return nil, fmt.Errorf("no modules on example.net")
863 }
864 if importPath == "rsc.io" {
865
866
867
868
869 return nil, fmt.Errorf("rsc.io is not a module")
870 }
871
872
873 if prefix := httpPrefix(importPath); prefix != "" {
874
875
876 return nil, fmt.Errorf("%q not allowed in import path", prefix+"//")
877 }
878 for _, srv := range vcsPaths {
879 if !str.HasPathPrefix(importPath, srv.pathPrefix) {
880 continue
881 }
882 m := srv.regexp.FindStringSubmatch(importPath)
883 if m == nil {
884 if srv.pathPrefix != "" {
885 return nil, importErrorf(importPath, "invalid %s import path %q", srv.pathPrefix, importPath)
886 }
887 continue
888 }
889
890
891 match := map[string]string{
892 "prefix": srv.pathPrefix + "/",
893 "import": importPath,
894 }
895 for i, name := range srv.regexp.SubexpNames() {
896 if name != "" && match[name] == "" {
897 match[name] = m[i]
898 }
899 }
900 if srv.vcs != "" {
901 match["vcs"] = expand(match, srv.vcs)
902 }
903 if srv.repo != "" {
904 match["repo"] = expand(match, srv.repo)
905 }
906 if srv.check != nil {
907 if err := srv.check(match); err != nil {
908 return nil, err
909 }
910 }
911 vcs := vcsByCmd(match["vcs"])
912 if vcs == nil {
913 return nil, fmt.Errorf("unknown version control system %q", match["vcs"])
914 }
915 if err := checkGOVCS(vcs, match["root"]); err != nil {
916 return nil, err
917 }
918 var repoURL string
919 if !srv.schemelessRepo {
920 repoURL = match["repo"]
921 } else {
922 repo := match["repo"]
923 var ok bool
924 repoURL, ok = interceptVCSTest(repo, vcs, security)
925 if !ok {
926 scheme, err := func() (string, error) {
927 for _, s := range vcs.Scheme {
928 if security == web.SecureOnly && !vcs.isSecureScheme(s) {
929 continue
930 }
931
932
933
934
935
936 if vcs.PingCmd == "" {
937 return s, nil
938 }
939 if err := vcs.Ping(s, repo); err == nil {
940 return s, nil
941 }
942 }
943 securityFrag := ""
944 if security == web.SecureOnly {
945 securityFrag = "secure "
946 }
947 return "", fmt.Errorf("no %sprotocol found for repository", securityFrag)
948 }()
949 if err != nil {
950 return nil, err
951 }
952 repoURL = scheme + "://" + repo
953 }
954 }
955 rr := &RepoRoot{
956 Repo: repoURL,
957 Root: match["root"],
958 VCS: vcs,
959 }
960 return rr, nil
961 }
962 return nil, errUnknownSite
963 }
964
965 func interceptVCSTest(repo string, vcs *Cmd, security web.SecurityMode) (repoURL string, ok bool) {
966 if VCSTestRepoURL == "" {
967 return "", false
968 }
969 if vcs == vcsMod {
970
971
972 return "", false
973 }
974
975 if scheme, path, ok := strings.Cut(repo, "://"); ok {
976 if security == web.SecureOnly && !vcs.isSecureScheme(scheme) {
977 return "", false
978 }
979 repo = path
980 }
981 for _, host := range VCSTestHosts {
982 if !str.HasPathPrefix(repo, host) {
983 continue
984 }
985
986 httpURL := VCSTestRepoURL + strings.TrimPrefix(repo, host)
987
988 if vcs == vcsSvn {
989
990
991 u, err := urlpkg.Parse(httpURL + "?vcwebsvn=1")
992 if err != nil {
993 panic(fmt.Sprintf("invalid vcs-test repo URL: %v", err))
994 }
995 svnURL, err := web.GetBytes(u)
996 svnURL = bytes.TrimSpace(svnURL)
997 if err == nil && len(svnURL) > 0 {
998 return string(svnURL) + strings.TrimPrefix(repo, host), true
999 }
1000
1001
1002
1003 }
1004
1005 return httpURL, true
1006 }
1007 return "", false
1008 }
1009
1010
1011
1012
1013
1014 func urlForImportPath(importPath string) (*urlpkg.URL, error) {
1015 slash := strings.Index(importPath, "/")
1016 if slash < 0 {
1017 slash = len(importPath)
1018 }
1019 host, path := importPath[:slash], importPath[slash:]
1020 if !strings.Contains(host, ".") {
1021 return nil, errors.New("import path does not begin with hostname")
1022 }
1023 if len(path) == 0 {
1024 path = "/"
1025 }
1026 return &urlpkg.URL{Host: host, Path: path, RawQuery: "go-get=1"}, nil
1027 }
1028
1029
1030
1031
1032
1033 func repoRootForImportDynamic(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
1034 url, err := urlForImportPath(importPath)
1035 if err != nil {
1036 return nil, err
1037 }
1038 resp, err := web.Get(security, url)
1039 if err != nil {
1040 msg := "https fetch: %v"
1041 if security == web.Insecure {
1042 msg = "http/" + msg
1043 }
1044 return nil, fmt.Errorf(msg, err)
1045 }
1046 body := resp.Body
1047 defer body.Close()
1048 imports, err := parseMetaGoImports(body, mod)
1049 if len(imports) == 0 {
1050 if respErr := resp.Err(); respErr != nil {
1051
1052
1053 return nil, respErr
1054 }
1055 }
1056 if err != nil {
1057 return nil, fmt.Errorf("parsing %s: %v", importPath, err)
1058 }
1059
1060 mmi, err := matchGoImport(imports, importPath)
1061 if err != nil {
1062 if _, ok := err.(ImportMismatchError); !ok {
1063 return nil, fmt.Errorf("parse %s: %v", url, err)
1064 }
1065 return nil, fmt.Errorf("parse %s: no go-import meta tags (%s)", resp.URL, err)
1066 }
1067 if cfg.BuildV {
1068 log.Printf("get %q: found meta tag %#v at %s", importPath, mmi, url)
1069 }
1070
1071
1072
1073
1074
1075
1076 if mmi.Prefix != importPath {
1077 if cfg.BuildV {
1078 log.Printf("get %q: verifying non-authoritative meta tag", importPath)
1079 }
1080 var imports []metaImport
1081 url, imports, err = metaImportsForPrefix(mmi.Prefix, mod, security)
1082 if err != nil {
1083 return nil, err
1084 }
1085 metaImport2, err := matchGoImport(imports, importPath)
1086 if err != nil || mmi != metaImport2 {
1087 return nil, fmt.Errorf("%s and %s disagree about go-import for %s", resp.URL, url, mmi.Prefix)
1088 }
1089 }
1090
1091 if err := validateRepoSubDir(mmi.SubDir); err != nil {
1092 return nil, fmt.Errorf("%s: invalid subdirectory %q: %v", resp.URL, mmi.SubDir, err)
1093 }
1094
1095 if err := validateRepoRoot(mmi.RepoRoot); err != nil {
1096 return nil, fmt.Errorf("%s: invalid repo root %q: %v", resp.URL, mmi.RepoRoot, err)
1097 }
1098 var vcs *Cmd
1099 if mmi.VCS == "mod" {
1100 vcs = vcsMod
1101 } else {
1102 vcs = vcsByCmd(mmi.VCS)
1103 if vcs == nil {
1104 return nil, fmt.Errorf("%s: unknown vcs %q", resp.URL, mmi.VCS)
1105 }
1106 }
1107
1108 if err := checkGOVCS(vcs, mmi.Prefix); err != nil {
1109 return nil, err
1110 }
1111
1112 repoURL, ok := interceptVCSTest(mmi.RepoRoot, vcs, security)
1113 if !ok {
1114 repoURL = mmi.RepoRoot
1115 }
1116 rr := &RepoRoot{
1117 Repo: repoURL,
1118 Root: mmi.Prefix,
1119 SubDir: mmi.SubDir,
1120 IsCustom: true,
1121 VCS: vcs,
1122 }
1123 return rr, nil
1124 }
1125
1126
1127
1128
1129 func validateRepoSubDir(subdir string) error {
1130 if subdir == "" {
1131 return nil
1132 }
1133 if subdir[0] == '/' {
1134 return errors.New("leading slash")
1135 }
1136 if subdir[0] == '-' {
1137 return errors.New("leading hyphen")
1138 }
1139 return nil
1140 }
1141
1142
1143
1144 func validateRepoRoot(repoRoot string) error {
1145 url, err := urlpkg.Parse(repoRoot)
1146 if err != nil {
1147 return err
1148 }
1149 if url.Scheme == "" {
1150 return errors.New("no scheme")
1151 }
1152 if url.Scheme == "file" {
1153 return errors.New("file scheme disallowed")
1154 }
1155 return nil
1156 }
1157
1158 var fetchGroup singleflight.Group
1159 var (
1160 fetchCacheMu sync.Mutex
1161 fetchCache = map[string]fetchResult{}
1162 )
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172 func metaImportsForPrefix(importPrefix string, mod ModuleMode, security web.SecurityMode) (*urlpkg.URL, []metaImport, error) {
1173 setCache := func(res fetchResult) (fetchResult, error) {
1174 fetchCacheMu.Lock()
1175 defer fetchCacheMu.Unlock()
1176 fetchCache[importPrefix] = res
1177 return res, nil
1178 }
1179
1180 resi, _, _ := fetchGroup.Do(importPrefix, func() (resi any, err error) {
1181 fetchCacheMu.Lock()
1182 if res, ok := fetchCache[importPrefix]; ok {
1183 fetchCacheMu.Unlock()
1184 return res, nil
1185 }
1186 fetchCacheMu.Unlock()
1187
1188 url, err := urlForImportPath(importPrefix)
1189 if err != nil {
1190 return setCache(fetchResult{err: err})
1191 }
1192 resp, err := web.Get(security, url)
1193 if err != nil {
1194 return setCache(fetchResult{url: url, err: fmt.Errorf("fetching %s: %v", importPrefix, err)})
1195 }
1196 body := resp.Body
1197 defer body.Close()
1198 imports, err := parseMetaGoImports(body, mod)
1199 if len(imports) == 0 {
1200 if respErr := resp.Err(); respErr != nil {
1201
1202
1203 return setCache(fetchResult{url: url, err: respErr})
1204 }
1205 }
1206 if err != nil {
1207 return setCache(fetchResult{url: url, err: fmt.Errorf("parsing %s: %v", resp.URL, err)})
1208 }
1209 if len(imports) == 0 {
1210 err = fmt.Errorf("fetching %s: no go-import meta tag found in %s", importPrefix, resp.URL)
1211 }
1212 return setCache(fetchResult{url: url, imports: imports, err: err})
1213 })
1214 res := resi.(fetchResult)
1215 return res.url, res.imports, res.err
1216 }
1217
1218 type fetchResult struct {
1219 url *urlpkg.URL
1220 imports []metaImport
1221 err error
1222 }
1223
1224
1225
1226 type metaImport struct {
1227 Prefix, VCS, RepoRoot, SubDir string
1228 }
1229
1230
1231
1232 type ImportMismatchError struct {
1233 importPath string
1234 mismatches []string
1235 }
1236
1237 func (m ImportMismatchError) Error() string {
1238 formattedStrings := make([]string, len(m.mismatches))
1239 for i, pre := range m.mismatches {
1240 formattedStrings[i] = fmt.Sprintf("meta tag %s did not match import path %s", pre, m.importPath)
1241 }
1242 return strings.Join(formattedStrings, ", ")
1243 }
1244
1245
1246
1247
1248 func matchGoImport(imports []metaImport, importPath string) (metaImport, error) {
1249 match := -1
1250
1251 errImportMismatch := ImportMismatchError{importPath: importPath}
1252 for i, im := range imports {
1253 if !str.HasPathPrefix(importPath, im.Prefix) {
1254 errImportMismatch.mismatches = append(errImportMismatch.mismatches, im.Prefix)
1255 continue
1256 }
1257
1258 if match >= 0 {
1259 if imports[match].VCS == "mod" && im.VCS != "mod" {
1260
1261
1262
1263 break
1264 }
1265 return metaImport{}, fmt.Errorf("multiple meta tags match import path %q", importPath)
1266 }
1267 match = i
1268 }
1269
1270 if match == -1 {
1271 return metaImport{}, errImportMismatch
1272 }
1273 return imports[match], nil
1274 }
1275
1276
1277 func expand(match map[string]string, s string) string {
1278
1279
1280
1281 oldNew := make([]string, 0, 2*len(match))
1282 for k, v := range match {
1283 oldNew = append(oldNew, "{"+k+"}", v)
1284 }
1285 return strings.NewReplacer(oldNew...).Replace(s)
1286 }
1287
1288
1289
1290
1291
1292 var vcsPaths = []*vcsPath{
1293
1294 {
1295 pathPrefix: "github.com",
1296 regexp: lazyregexp.New(`^(?P<root>github\.com/[\w.\-]+/[\w.\-]+)(/[\w.\-]+)*$`),
1297 vcs: "git",
1298 repo: "https://{root}",
1299 check: noVCSSuffix,
1300 },
1301
1302
1303 {
1304 pathPrefix: "bitbucket.org",
1305 regexp: lazyregexp.New(`^(?P<root>bitbucket\.org/(?P<bitname>[\w.\-]+/[\w.\-]+))(/[\w.\-]+)*$`),
1306 vcs: "git",
1307 repo: "https://{root}",
1308 check: noVCSSuffix,
1309 },
1310
1311
1312 {
1313 pathPrefix: "hub.jazz.net/git",
1314 regexp: lazyregexp.New(`^(?P<root>hub\.jazz\.net/git/[a-z0-9]+/[\w.\-]+)(/[\w.\-]+)*$`),
1315 vcs: "git",
1316 repo: "https://{root}",
1317 check: noVCSSuffix,
1318 },
1319
1320
1321 {
1322 pathPrefix: "git.apache.org",
1323 regexp: lazyregexp.New(`^(?P<root>git\.apache\.org/[a-z0-9_.\-]+\.git)(/[\w.\-]+)*$`),
1324 vcs: "git",
1325 repo: "https://{root}",
1326 },
1327
1328
1329 {
1330 pathPrefix: "git.openstack.org",
1331 regexp: lazyregexp.New(`^(?P<root>git\.openstack\.org/[\w.\-]+/[\w.\-]+)(\.git)?(/[\w.\-]+)*$`),
1332 vcs: "git",
1333 repo: "https://{root}",
1334 },
1335
1336
1337 {
1338 pathPrefix: "chiselapp.com",
1339 regexp: lazyregexp.New(`^(?P<root>chiselapp\.com/user/[A-Za-z0-9]+/repository/[\w.\-]+)$`),
1340 vcs: "fossil",
1341 repo: "https://{root}",
1342 },
1343
1344
1345
1346 {
1347 regexp: lazyregexp.New(`(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[\w.\-]+)+?)\.(?P<vcs>bzr|fossil|git|hg|svn))(/~?[\w.\-]+)*$`),
1348 schemelessRepo: true,
1349 },
1350 }
1351
1352
1353
1354
1355
1356 var vcsPathsAfterDynamic = []*vcsPath{
1357
1358 {
1359 pathPrefix: "launchpad.net",
1360 regexp: lazyregexp.New(`^(?P<root>launchpad\.net/((?P<project>[\w.\-]+)(?P<series>/[\w.\-]+)?|~[\w.\-]+/(\+junk|[\w.\-]+)/[\w.\-]+))(/[\w.\-]+)*$`),
1361 vcs: "bzr",
1362 repo: "https://{root}",
1363 check: launchpadVCS,
1364 },
1365 }
1366
1367
1368
1369
1370 func noVCSSuffix(match map[string]string) error {
1371 repo := match["repo"]
1372 for _, vcs := range vcsList {
1373 if strings.HasSuffix(repo, "."+vcs.Cmd) {
1374 return fmt.Errorf("invalid version control suffix in %s path", match["prefix"])
1375 }
1376 }
1377 return nil
1378 }
1379
1380
1381
1382
1383
1384 func launchpadVCS(match map[string]string) error {
1385 if match["project"] == "" || match["series"] == "" {
1386 return nil
1387 }
1388 url := &urlpkg.URL{
1389 Scheme: "https",
1390 Host: "code.launchpad.net",
1391 Path: expand(match, "/{project}{series}/.bzr/branch-format"),
1392 }
1393 _, err := web.GetBytes(url)
1394 if err != nil {
1395 match["root"] = expand(match, "launchpad.net/{project}")
1396 match["repo"] = expand(match, "https://{root}")
1397 }
1398 return nil
1399 }
1400
1401
1402
1403 type importError struct {
1404 importPath string
1405 err error
1406 }
1407
1408 func importErrorf(path, format string, args ...any) error {
1409 err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
1410 if errStr := err.Error(); !strings.Contains(errStr, path) {
1411 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
1412 }
1413 return err
1414 }
1415
1416 func (e *importError) Error() string {
1417 return e.err.Error()
1418 }
1419
1420 func (e *importError) Unwrap() error {
1421
1422
1423 return errors.Unwrap(e.err)
1424 }
1425
1426 func (e *importError) ImportPath() string {
1427 return e.importPath
1428 }
1429
View as plain text