github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/src/cmd/go/internal/get/vcs.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package get
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/json"
    10  	"errors"
    11  	"fmt"
    12  	"internal/singleflight"
    13  	"log"
    14  	"net/url"
    15  	"os"
    16  	"os/exec"
    17  	"path/filepath"
    18  	"regexp"
    19  	"strings"
    20  	"sync"
    21  
    22  	"cmd/go/internal/base"
    23  	"cmd/go/internal/cfg"
    24  	"cmd/go/internal/web"
    25  )
    26  
    27  // A vcsCmd describes how to use a version control system
    28  // like Mercurial, Git, or Subversion.
    29  type vcsCmd struct {
    30  	name string
    31  	cmd  string // name of binary to invoke command
    32  
    33  	createCmd   []string // commands to download a fresh copy of a repository
    34  	downloadCmd []string // commands to download updates into an existing repository
    35  
    36  	tagCmd         []tagCmd // commands to list tags
    37  	tagLookupCmd   []tagCmd // commands to lookup tags before running tagSyncCmd
    38  	tagSyncCmd     []string // commands to sync to specific tag
    39  	tagSyncDefault []string // commands to sync to default tag
    40  
    41  	scheme  []string
    42  	pingCmd string
    43  
    44  	remoteRepo  func(v *vcsCmd, rootDir string) (remoteRepo string, err error)
    45  	resolveRepo func(v *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error)
    46  }
    47  
    48  var defaultSecureScheme = map[string]bool{
    49  	"https":   true,
    50  	"git+ssh": true,
    51  	"bzr+ssh": true,
    52  	"svn+ssh": true,
    53  	"ssh":     true,
    54  }
    55  
    56  func (v *vcsCmd) isSecure(repo string) bool {
    57  	u, err := url.Parse(repo)
    58  	if err != nil {
    59  		// If repo is not a URL, it's not secure.
    60  		return false
    61  	}
    62  	return v.isSecureScheme(u.Scheme)
    63  }
    64  
    65  func (v *vcsCmd) isSecureScheme(scheme string) bool {
    66  	switch v.cmd {
    67  	case "git":
    68  		// GIT_ALLOW_PROTOCOL is an environment variable defined by Git. It is a
    69  		// colon-separated list of schemes that are allowed to be used with git
    70  		// fetch/clone. Any scheme not mentioned will be considered insecure.
    71  		if allow := os.Getenv("GIT_ALLOW_PROTOCOL"); allow != "" {
    72  			for _, s := range strings.Split(allow, ":") {
    73  				if s == scheme {
    74  					return true
    75  				}
    76  			}
    77  			return false
    78  		}
    79  	}
    80  	return defaultSecureScheme[scheme]
    81  }
    82  
    83  // A tagCmd describes a command to list available tags
    84  // that can be passed to tagSyncCmd.
    85  type tagCmd struct {
    86  	cmd     string // command to list tags
    87  	pattern string // regexp to extract tags from list
    88  }
    89  
    90  // vcsList lists the known version control systems
    91  var vcsList = []*vcsCmd{
    92  	vcsHg,
    93  	vcsGit,
    94  	vcsSvn,
    95  	vcsBzr,
    96  }
    97  
    98  // vcsByCmd returns the version control system for the given
    99  // command name (hg, git, svn, bzr).
   100  func vcsByCmd(cmd string) *vcsCmd {
   101  	for _, vcs := range vcsList {
   102  		if vcs.cmd == cmd {
   103  			return vcs
   104  		}
   105  	}
   106  	return nil
   107  }
   108  
   109  // vcsHg describes how to use Mercurial.
   110  var vcsHg = &vcsCmd{
   111  	name: "Mercurial",
   112  	cmd:  "hg",
   113  
   114  	createCmd:   []string{"clone -U {repo} {dir}"},
   115  	downloadCmd: []string{"pull"},
   116  
   117  	// We allow both tag and branch names as 'tags'
   118  	// for selecting a version. This lets people have
   119  	// a go.release.r60 branch and a go1 branch
   120  	// and make changes in both, without constantly
   121  	// editing .hgtags.
   122  	tagCmd: []tagCmd{
   123  		{"tags", `^(\S+)`},
   124  		{"branches", `^(\S+)`},
   125  	},
   126  	tagSyncCmd:     []string{"update -r {tag}"},
   127  	tagSyncDefault: []string{"update default"},
   128  
   129  	scheme:     []string{"https", "http", "ssh"},
   130  	pingCmd:    "identify {scheme}://{repo}",
   131  	remoteRepo: hgRemoteRepo,
   132  }
   133  
   134  func hgRemoteRepo(vcsHg *vcsCmd, rootDir string) (remoteRepo string, err error) {
   135  	out, err := vcsHg.runOutput(rootDir, "paths default")
   136  	if err != nil {
   137  		return "", err
   138  	}
   139  	return strings.TrimSpace(string(out)), nil
   140  }
   141  
   142  // vcsGit describes how to use Git.
   143  var vcsGit = &vcsCmd{
   144  	name: "Git",
   145  	cmd:  "git",
   146  
   147  	createCmd:   []string{"clone {repo} {dir}", "-go-internal-cd {dir} submodule update --init --recursive"},
   148  	downloadCmd: []string{"pull --ff-only", "submodule update --init --recursive"},
   149  
   150  	tagCmd: []tagCmd{
   151  		// tags/xxx matches a git tag named xxx
   152  		// origin/xxx matches a git branch named xxx on the default remote repository
   153  		{"show-ref", `(?:tags|origin)/(\S+)$`},
   154  	},
   155  	tagLookupCmd: []tagCmd{
   156  		{"show-ref tags/{tag} origin/{tag}", `((?:tags|origin)/\S+)$`},
   157  	},
   158  	tagSyncCmd: []string{"checkout {tag}", "submodule update --init --recursive"},
   159  	// both createCmd and downloadCmd update the working dir.
   160  	// No need to do more here. We used to 'checkout master'
   161  	// but that doesn't work if the default branch is not named master.
   162  	// DO NOT add 'checkout master' here.
   163  	// See golang.org/issue/9032.
   164  	tagSyncDefault: []string{"submodule update --init --recursive"},
   165  
   166  	scheme:     []string{"git", "https", "http", "git+ssh", "ssh"},
   167  	pingCmd:    "ls-remote {scheme}://{repo}",
   168  	remoteRepo: gitRemoteRepo,
   169  }
   170  
   171  // scpSyntaxRe matches the SCP-like addresses used by Git to access
   172  // repositories by SSH.
   173  var scpSyntaxRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`)
   174  
   175  func gitRemoteRepo(vcsGit *vcsCmd, rootDir string) (remoteRepo string, err error) {
   176  	cmd := "config remote.origin.url"
   177  	errParse := errors.New("unable to parse output of git " + cmd)
   178  	errRemoteOriginNotFound := errors.New("remote origin not found")
   179  	outb, err := vcsGit.run1(rootDir, cmd, nil, false)
   180  	if err != nil {
   181  		// if it doesn't output any message, it means the config argument is correct,
   182  		// but the config value itself doesn't exist
   183  		if outb != nil && len(outb) == 0 {
   184  			return "", errRemoteOriginNotFound
   185  		}
   186  		return "", err
   187  	}
   188  	out := strings.TrimSpace(string(outb))
   189  
   190  	var repoURL *url.URL
   191  	if m := scpSyntaxRe.FindStringSubmatch(out); m != nil {
   192  		// Match SCP-like syntax and convert it to a URL.
   193  		// Eg, "git@github.com:user/repo" becomes
   194  		// "ssh://git@github.com/user/repo".
   195  		repoURL = &url.URL{
   196  			Scheme: "ssh",
   197  			User:   url.User(m[1]),
   198  			Host:   m[2],
   199  			Path:   m[3],
   200  		}
   201  	} else {
   202  		repoURL, err = url.Parse(out)
   203  		if err != nil {
   204  			return "", err
   205  		}
   206  	}
   207  
   208  	// Iterate over insecure schemes too, because this function simply
   209  	// reports the state of the repo. If we can't see insecure schemes then
   210  	// we can't report the actual repo URL.
   211  	for _, s := range vcsGit.scheme {
   212  		if repoURL.Scheme == s {
   213  			return repoURL.String(), nil
   214  		}
   215  	}
   216  	return "", errParse
   217  }
   218  
   219  // vcsBzr describes how to use Bazaar.
   220  var vcsBzr = &vcsCmd{
   221  	name: "Bazaar",
   222  	cmd:  "bzr",
   223  
   224  	createCmd: []string{"branch {repo} {dir}"},
   225  
   226  	// Without --overwrite bzr will not pull tags that changed.
   227  	// Replace by --overwrite-tags after http://pad.lv/681792 goes in.
   228  	downloadCmd: []string{"pull --overwrite"},
   229  
   230  	tagCmd:         []tagCmd{{"tags", `^(\S+)`}},
   231  	tagSyncCmd:     []string{"update -r {tag}"},
   232  	tagSyncDefault: []string{"update -r revno:-1"},
   233  
   234  	scheme:      []string{"https", "http", "bzr", "bzr+ssh"},
   235  	pingCmd:     "info {scheme}://{repo}",
   236  	remoteRepo:  bzrRemoteRepo,
   237  	resolveRepo: bzrResolveRepo,
   238  }
   239  
   240  func bzrRemoteRepo(vcsBzr *vcsCmd, rootDir string) (remoteRepo string, err error) {
   241  	outb, err := vcsBzr.runOutput(rootDir, "config parent_location")
   242  	if err != nil {
   243  		return "", err
   244  	}
   245  	return strings.TrimSpace(string(outb)), nil
   246  }
   247  
   248  func bzrResolveRepo(vcsBzr *vcsCmd, rootDir, remoteRepo string) (realRepo string, err error) {
   249  	outb, err := vcsBzr.runOutput(rootDir, "info "+remoteRepo)
   250  	if err != nil {
   251  		return "", err
   252  	}
   253  	out := string(outb)
   254  
   255  	// Expect:
   256  	// ...
   257  	//   (branch root|repository branch): <URL>
   258  	// ...
   259  
   260  	found := false
   261  	for _, prefix := range []string{"\n  branch root: ", "\n  repository branch: "} {
   262  		i := strings.Index(out, prefix)
   263  		if i >= 0 {
   264  			out = out[i+len(prefix):]
   265  			found = true
   266  			break
   267  		}
   268  	}
   269  	if !found {
   270  		return "", fmt.Errorf("unable to parse output of bzr info")
   271  	}
   272  
   273  	i := strings.Index(out, "\n")
   274  	if i < 0 {
   275  		return "", fmt.Errorf("unable to parse output of bzr info")
   276  	}
   277  	out = out[:i]
   278  	return strings.TrimSpace(out), nil
   279  }
   280  
   281  // vcsSvn describes how to use Subversion.
   282  var vcsSvn = &vcsCmd{
   283  	name: "Subversion",
   284  	cmd:  "svn",
   285  
   286  	createCmd:   []string{"checkout {repo} {dir}"},
   287  	downloadCmd: []string{"update"},
   288  
   289  	// There is no tag command in subversion.
   290  	// The branch information is all in the path names.
   291  
   292  	scheme:     []string{"https", "http", "svn", "svn+ssh"},
   293  	pingCmd:    "info {scheme}://{repo}",
   294  	remoteRepo: svnRemoteRepo,
   295  }
   296  
   297  func svnRemoteRepo(vcsSvn *vcsCmd, rootDir string) (remoteRepo string, err error) {
   298  	outb, err := vcsSvn.runOutput(rootDir, "info")
   299  	if err != nil {
   300  		return "", err
   301  	}
   302  	out := string(outb)
   303  
   304  	// Expect:
   305  	// ...
   306  	// Repository Root: <URL>
   307  	// ...
   308  
   309  	i := strings.Index(out, "\nRepository Root: ")
   310  	if i < 0 {
   311  		return "", fmt.Errorf("unable to parse output of svn info")
   312  	}
   313  	out = out[i+len("\nRepository Root: "):]
   314  	i = strings.Index(out, "\n")
   315  	if i < 0 {
   316  		return "", fmt.Errorf("unable to parse output of svn info")
   317  	}
   318  	out = out[:i]
   319  	return strings.TrimSpace(out), nil
   320  }
   321  
   322  func (v *vcsCmd) String() string {
   323  	return v.name
   324  }
   325  
   326  // run runs the command line cmd in the given directory.
   327  // keyval is a list of key, value pairs.  run expands
   328  // instances of {key} in cmd into value, but only after
   329  // splitting cmd into individual arguments.
   330  // If an error occurs, run prints the command line and the
   331  // command's combined stdout+stderr to standard error.
   332  // Otherwise run discards the command's output.
   333  func (v *vcsCmd) run(dir string, cmd string, keyval ...string) error {
   334  	_, err := v.run1(dir, cmd, keyval, true)
   335  	return err
   336  }
   337  
   338  // runVerboseOnly is like run but only generates error output to standard error in verbose mode.
   339  func (v *vcsCmd) runVerboseOnly(dir string, cmd string, keyval ...string) error {
   340  	_, err := v.run1(dir, cmd, keyval, false)
   341  	return err
   342  }
   343  
   344  // runOutput is like run but returns the output of the command.
   345  func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {
   346  	return v.run1(dir, cmd, keyval, true)
   347  }
   348  
   349  // run1 is the generalized implementation of run and runOutput.
   350  func (v *vcsCmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([]byte, error) {
   351  	m := make(map[string]string)
   352  	for i := 0; i < len(keyval); i += 2 {
   353  		m[keyval[i]] = keyval[i+1]
   354  	}
   355  	args := strings.Fields(cmdline)
   356  	for i, arg := range args {
   357  		args[i] = expand(m, arg)
   358  	}
   359  
   360  	if len(args) >= 2 && args[0] == "-go-internal-cd" {
   361  		if filepath.IsAbs(args[1]) {
   362  			dir = args[1]
   363  		} else {
   364  			dir = filepath.Join(dir, args[1])
   365  		}
   366  		args = args[2:]
   367  	}
   368  
   369  	_, err := exec.LookPath(v.cmd)
   370  	if err != nil {
   371  		fmt.Fprintf(os.Stderr,
   372  			"go: missing %s command. See https://golang.org/s/gogetcmd\n",
   373  			v.name)
   374  		return nil, err
   375  	}
   376  
   377  	cmd := exec.Command(v.cmd, args...)
   378  	cmd.Dir = dir
   379  	cmd.Env = base.EnvForDir(cmd.Dir, os.Environ())
   380  	if cfg.BuildX {
   381  		fmt.Printf("cd %s\n", dir)
   382  		fmt.Printf("%s %s\n", v.cmd, strings.Join(args, " "))
   383  	}
   384  	var buf bytes.Buffer
   385  	cmd.Stdout = &buf
   386  	cmd.Stderr = &buf
   387  	err = cmd.Run()
   388  	out := buf.Bytes()
   389  	if err != nil {
   390  		if verbose || cfg.BuildV {
   391  			fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.cmd, strings.Join(args, " "))
   392  			os.Stderr.Write(out)
   393  		}
   394  		return out, err
   395  	}
   396  	return out, nil
   397  }
   398  
   399  // ping pings to determine scheme to use.
   400  func (v *vcsCmd) ping(scheme, repo string) error {
   401  	return v.runVerboseOnly(".", v.pingCmd, "scheme", scheme, "repo", repo)
   402  }
   403  
   404  // create creates a new copy of repo in dir.
   405  // The parent of dir must exist; dir must not.
   406  func (v *vcsCmd) create(dir, repo string) error {
   407  	for _, cmd := range v.createCmd {
   408  		if err := v.run(".", cmd, "dir", dir, "repo", repo); err != nil {
   409  			return err
   410  		}
   411  	}
   412  	return nil
   413  }
   414  
   415  // download downloads any new changes for the repo in dir.
   416  func (v *vcsCmd) download(dir string) error {
   417  	for _, cmd := range v.downloadCmd {
   418  		if err := v.run(dir, cmd); err != nil {
   419  			return err
   420  		}
   421  	}
   422  	return nil
   423  }
   424  
   425  // tags returns the list of available tags for the repo in dir.
   426  func (v *vcsCmd) tags(dir string) ([]string, error) {
   427  	var tags []string
   428  	for _, tc := range v.tagCmd {
   429  		out, err := v.runOutput(dir, tc.cmd)
   430  		if err != nil {
   431  			return nil, err
   432  		}
   433  		re := regexp.MustCompile(`(?m-s)` + tc.pattern)
   434  		for _, m := range re.FindAllStringSubmatch(string(out), -1) {
   435  			tags = append(tags, m[1])
   436  		}
   437  	}
   438  	return tags, nil
   439  }
   440  
   441  // tagSync syncs the repo in dir to the named tag,
   442  // which either is a tag returned by tags or is v.tagDefault.
   443  func (v *vcsCmd) tagSync(dir, tag string) error {
   444  	if v.tagSyncCmd == nil {
   445  		return nil
   446  	}
   447  	if tag != "" {
   448  		for _, tc := range v.tagLookupCmd {
   449  			out, err := v.runOutput(dir, tc.cmd, "tag", tag)
   450  			if err != nil {
   451  				return err
   452  			}
   453  			re := regexp.MustCompile(`(?m-s)` + tc.pattern)
   454  			m := re.FindStringSubmatch(string(out))
   455  			if len(m) > 1 {
   456  				tag = m[1]
   457  				break
   458  			}
   459  		}
   460  	}
   461  
   462  	if tag == "" && v.tagSyncDefault != nil {
   463  		for _, cmd := range v.tagSyncDefault {
   464  			if err := v.run(dir, cmd); err != nil {
   465  				return err
   466  			}
   467  		}
   468  		return nil
   469  	}
   470  
   471  	for _, cmd := range v.tagSyncCmd {
   472  		if err := v.run(dir, cmd, "tag", tag); err != nil {
   473  			return err
   474  		}
   475  	}
   476  	return nil
   477  }
   478  
   479  // A vcsPath describes how to convert an import path into a
   480  // version control system and repository name.
   481  type vcsPath struct {
   482  	prefix string                              // prefix this description applies to
   483  	re     string                              // pattern for import path
   484  	repo   string                              // repository to use (expand with match of re)
   485  	vcs    string                              // version control system to use (expand with match of re)
   486  	check  func(match map[string]string) error // additional checks
   487  	ping   bool                                // ping for scheme to use to download repo
   488  
   489  	regexp *regexp.Regexp // cached compiled form of re
   490  }
   491  
   492  // vcsFromDir inspects dir and its parents to determine the
   493  // version control system and code repository to use.
   494  // On return, root is the import path
   495  // corresponding to the root of the repository.
   496  func vcsFromDir(dir, srcRoot string) (vcs *vcsCmd, root string, err error) {
   497  	// Clean and double-check that dir is in (a subdirectory of) srcRoot.
   498  	dir = filepath.Clean(dir)
   499  	srcRoot = filepath.Clean(srcRoot)
   500  	if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator {
   501  		return nil, "", fmt.Errorf("directory %q is outside source root %q", dir, srcRoot)
   502  	}
   503  
   504  	origDir := dir
   505  	for len(dir) > len(srcRoot) {
   506  		for _, vcs := range vcsList {
   507  			if _, err := os.Stat(filepath.Join(dir, "."+vcs.cmd)); err == nil {
   508  				return vcs, filepath.ToSlash(dir[len(srcRoot)+1:]), nil
   509  			}
   510  		}
   511  
   512  		// Move to parent.
   513  		ndir := filepath.Dir(dir)
   514  		if len(ndir) >= len(dir) {
   515  			// Shouldn't happen, but just in case, stop.
   516  			break
   517  		}
   518  		dir = ndir
   519  	}
   520  
   521  	return nil, "", fmt.Errorf("directory %q is not using a known version control system", origDir)
   522  }
   523  
   524  // repoRoot represents a version control system, a repo, and a root of
   525  // where to put it on disk.
   526  type repoRoot struct {
   527  	vcs *vcsCmd
   528  
   529  	// repo is the repository URL, including scheme
   530  	repo string
   531  
   532  	// root is the import path corresponding to the root of the
   533  	// repository
   534  	root string
   535  
   536  	// isCustom is true for custom import paths (those defined by HTML meta tags)
   537  	isCustom bool
   538  }
   539  
   540  var httpPrefixRE = regexp.MustCompile(`^https?:`)
   541  
   542  // repoRootForImportPath analyzes importPath to determine the
   543  // version control system, and code repository to use.
   544  func repoRootForImportPath(importPath string, security web.SecurityMode) (*repoRoot, error) {
   545  	rr, err := repoRootFromVCSPaths(importPath, "", security, vcsPaths)
   546  	if err == errUnknownSite {
   547  		// If there are wildcards, look up the thing before the wildcard,
   548  		// hoping it applies to the wildcarded parts too.
   549  		// This makes 'go get rsc.io/pdf/...' work in a fresh GOPATH.
   550  		lookup := strings.TrimSuffix(importPath, "/...")
   551  		if i := strings.Index(lookup, "/.../"); i >= 0 {
   552  			lookup = lookup[:i]
   553  		}
   554  		rr, err = repoRootForImportDynamic(lookup, security)
   555  		if err != nil {
   556  			err = fmt.Errorf("unrecognized import path %q (%v)", importPath, err)
   557  		}
   558  	}
   559  	if err != nil {
   560  		rr1, err1 := repoRootFromVCSPaths(importPath, "", security, vcsPathsAfterDynamic)
   561  		if err1 == nil {
   562  			rr = rr1
   563  			err = nil
   564  		}
   565  	}
   566  
   567  	if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.root, "...") {
   568  		// Do not allow wildcards in the repo root.
   569  		rr = nil
   570  		err = fmt.Errorf("cannot expand ... in %q", importPath)
   571  	}
   572  	return rr, err
   573  }
   574  
   575  var errUnknownSite = errors.New("dynamic lookup required to find mapping")
   576  
   577  // repoRootFromVCSPaths attempts to map importPath to a repoRoot
   578  // using the mappings defined in vcsPaths.
   579  // If scheme is non-empty, that scheme is forced.
   580  func repoRootFromVCSPaths(importPath, scheme string, security web.SecurityMode, vcsPaths []*vcsPath) (*repoRoot, error) {
   581  	// A common error is to use https://packagepath because that's what
   582  	// hg and git require. Diagnose this helpfully.
   583  	if loc := httpPrefixRE.FindStringIndex(importPath); loc != nil {
   584  		// The importPath has been cleaned, so has only one slash. The pattern
   585  		// ignores the slashes; the error message puts them back on the RHS at least.
   586  		return nil, fmt.Errorf("%q not allowed in import path", importPath[loc[0]:loc[1]]+"//")
   587  	}
   588  	for _, srv := range vcsPaths {
   589  		if !strings.HasPrefix(importPath, srv.prefix) {
   590  			continue
   591  		}
   592  		m := srv.regexp.FindStringSubmatch(importPath)
   593  		if m == nil {
   594  			if srv.prefix != "" {
   595  				return nil, fmt.Errorf("invalid %s import path %q", srv.prefix, importPath)
   596  			}
   597  			continue
   598  		}
   599  
   600  		// Build map of named subexpression matches for expand.
   601  		match := map[string]string{
   602  			"prefix": srv.prefix,
   603  			"import": importPath,
   604  		}
   605  		for i, name := range srv.regexp.SubexpNames() {
   606  			if name != "" && match[name] == "" {
   607  				match[name] = m[i]
   608  			}
   609  		}
   610  		if srv.vcs != "" {
   611  			match["vcs"] = expand(match, srv.vcs)
   612  		}
   613  		if srv.repo != "" {
   614  			match["repo"] = expand(match, srv.repo)
   615  		}
   616  		if srv.check != nil {
   617  			if err := srv.check(match); err != nil {
   618  				return nil, err
   619  			}
   620  		}
   621  		vcs := vcsByCmd(match["vcs"])
   622  		if vcs == nil {
   623  			return nil, fmt.Errorf("unknown version control system %q", match["vcs"])
   624  		}
   625  		if srv.ping {
   626  			if scheme != "" {
   627  				match["repo"] = scheme + "://" + match["repo"]
   628  			} else {
   629  				for _, scheme := range vcs.scheme {
   630  					if security == web.Secure && !vcs.isSecureScheme(scheme) {
   631  						continue
   632  					}
   633  					if vcs.ping(scheme, match["repo"]) == nil {
   634  						match["repo"] = scheme + "://" + match["repo"]
   635  						break
   636  					}
   637  				}
   638  			}
   639  		}
   640  		rr := &repoRoot{
   641  			vcs:  vcs,
   642  			repo: match["repo"],
   643  			root: match["root"],
   644  		}
   645  		return rr, nil
   646  	}
   647  	return nil, errUnknownSite
   648  }
   649  
   650  // repoRootForImportDynamic finds a *repoRoot for a custom domain that's not
   651  // statically known by repoRootForImportPathStatic.
   652  //
   653  // This handles custom import paths like "name.tld/pkg/foo" or just "name.tld".
   654  func repoRootForImportDynamic(importPath string, security web.SecurityMode) (*repoRoot, error) {
   655  	slash := strings.Index(importPath, "/")
   656  	if slash < 0 {
   657  		slash = len(importPath)
   658  	}
   659  	host := importPath[:slash]
   660  	if !strings.Contains(host, ".") {
   661  		return nil, errors.New("import path does not begin with hostname")
   662  	}
   663  	urlStr, body, err := web.GetMaybeInsecure(importPath, security)
   664  	if err != nil {
   665  		msg := "https fetch: %v"
   666  		if security == web.Insecure {
   667  			msg = "http/" + msg
   668  		}
   669  		return nil, fmt.Errorf(msg, err)
   670  	}
   671  	defer body.Close()
   672  	imports, err := parseMetaGoImports(body)
   673  	if err != nil {
   674  		return nil, fmt.Errorf("parsing %s: %v", importPath, err)
   675  	}
   676  	// Find the matched meta import.
   677  	mmi, err := matchGoImport(imports, importPath)
   678  	if err != nil {
   679  		if _, ok := err.(ImportMismatchError); !ok {
   680  			return nil, fmt.Errorf("parse %s: %v", urlStr, err)
   681  		}
   682  		return nil, fmt.Errorf("parse %s: no go-import meta tags (%s)", urlStr, err)
   683  	}
   684  	if cfg.BuildV {
   685  		log.Printf("get %q: found meta tag %#v at %s", importPath, mmi, urlStr)
   686  	}
   687  	// If the import was "uni.edu/bob/project", which said the
   688  	// prefix was "uni.edu" and the RepoRoot was "evilroot.com",
   689  	// make sure we don't trust Bob and check out evilroot.com to
   690  	// "uni.edu" yet (possibly overwriting/preempting another
   691  	// non-evil student).  Instead, first verify the root and see
   692  	// if it matches Bob's claim.
   693  	if mmi.Prefix != importPath {
   694  		if cfg.BuildV {
   695  			log.Printf("get %q: verifying non-authoritative meta tag", importPath)
   696  		}
   697  		urlStr0 := urlStr
   698  		var imports []metaImport
   699  		urlStr, imports, err = metaImportsForPrefix(mmi.Prefix, security)
   700  		if err != nil {
   701  			return nil, err
   702  		}
   703  		metaImport2, err := matchGoImport(imports, importPath)
   704  		if err != nil || mmi != metaImport2 {
   705  			return nil, fmt.Errorf("%s and %s disagree about go-import for %s", urlStr0, urlStr, mmi.Prefix)
   706  		}
   707  	}
   708  
   709  	if !strings.Contains(mmi.RepoRoot, "://") {
   710  		return nil, fmt.Errorf("%s: invalid repo root %q; no scheme", urlStr, mmi.RepoRoot)
   711  	}
   712  	rr := &repoRoot{
   713  		vcs:      vcsByCmd(mmi.VCS),
   714  		repo:     mmi.RepoRoot,
   715  		root:     mmi.Prefix,
   716  		isCustom: true,
   717  	}
   718  	if rr.vcs == nil {
   719  		return nil, fmt.Errorf("%s: unknown vcs %q", urlStr, mmi.VCS)
   720  	}
   721  	return rr, nil
   722  }
   723  
   724  var fetchGroup singleflight.Group
   725  var (
   726  	fetchCacheMu sync.Mutex
   727  	fetchCache   = map[string]fetchResult{} // key is metaImportsForPrefix's importPrefix
   728  )
   729  
   730  // metaImportsForPrefix takes a package's root import path as declared in a <meta> tag
   731  // and returns its HTML discovery URL and the parsed metaImport lines
   732  // found on the page.
   733  //
   734  // The importPath is of the form "golang.org/x/tools".
   735  // It is an error if no imports are found.
   736  // urlStr will still be valid if err != nil.
   737  // The returned urlStr will be of the form "https://golang.org/x/tools?go-get=1"
   738  func metaImportsForPrefix(importPrefix string, security web.SecurityMode) (urlStr string, imports []metaImport, err error) {
   739  	setCache := func(res fetchResult) (fetchResult, error) {
   740  		fetchCacheMu.Lock()
   741  		defer fetchCacheMu.Unlock()
   742  		fetchCache[importPrefix] = res
   743  		return res, nil
   744  	}
   745  
   746  	resi, _, _ := fetchGroup.Do(importPrefix, func() (resi interface{}, err error) {
   747  		fetchCacheMu.Lock()
   748  		if res, ok := fetchCache[importPrefix]; ok {
   749  			fetchCacheMu.Unlock()
   750  			return res, nil
   751  		}
   752  		fetchCacheMu.Unlock()
   753  
   754  		urlStr, body, err := web.GetMaybeInsecure(importPrefix, security)
   755  		if err != nil {
   756  			return setCache(fetchResult{urlStr: urlStr, err: fmt.Errorf("fetch %s: %v", urlStr, err)})
   757  		}
   758  		imports, err := parseMetaGoImports(body)
   759  		if err != nil {
   760  			return setCache(fetchResult{urlStr: urlStr, err: fmt.Errorf("parsing %s: %v", urlStr, err)})
   761  		}
   762  		if len(imports) == 0 {
   763  			err = fmt.Errorf("fetch %s: no go-import meta tag", urlStr)
   764  		}
   765  		return setCache(fetchResult{urlStr: urlStr, imports: imports, err: err})
   766  	})
   767  	res := resi.(fetchResult)
   768  	return res.urlStr, res.imports, res.err
   769  }
   770  
   771  type fetchResult struct {
   772  	urlStr  string // e.g. "https://foo.com/x/bar?go-get=1"
   773  	imports []metaImport
   774  	err     error
   775  }
   776  
   777  // metaImport represents the parsed <meta name="go-import"
   778  // content="prefix vcs reporoot" /> tags from HTML files.
   779  type metaImport struct {
   780  	Prefix, VCS, RepoRoot string
   781  }
   782  
   783  func splitPathHasPrefix(path, prefix []string) bool {
   784  	if len(path) < len(prefix) {
   785  		return false
   786  	}
   787  	for i, p := range prefix {
   788  		if path[i] != p {
   789  			return false
   790  		}
   791  	}
   792  	return true
   793  }
   794  
   795  // A ImportMismatchError is returned where metaImport/s are present
   796  // but none match our import path.
   797  type ImportMismatchError struct {
   798  	importPath string
   799  	mismatches []string // the meta imports that were discarded for not matching our importPath
   800  }
   801  
   802  func (m ImportMismatchError) Error() string {
   803  	formattedStrings := make([]string, len(m.mismatches))
   804  	for i, pre := range m.mismatches {
   805  		formattedStrings[i] = fmt.Sprintf("meta tag %s did not match import path %s", pre, m.importPath)
   806  	}
   807  	return strings.Join(formattedStrings, ", ")
   808  }
   809  
   810  // matchGoImport returns the metaImport from imports matching importPath.
   811  // An error is returned if there are multiple matches.
   812  // errNoMatch is returned if none match.
   813  func matchGoImport(imports []metaImport, importPath string) (metaImport, error) {
   814  	match := -1
   815  	imp := strings.Split(importPath, "/")
   816  
   817  	errImportMismatch := ImportMismatchError{importPath: importPath}
   818  	for i, im := range imports {
   819  		pre := strings.Split(im.Prefix, "/")
   820  
   821  		if !splitPathHasPrefix(imp, pre) {
   822  			errImportMismatch.mismatches = append(errImportMismatch.mismatches, im.Prefix)
   823  			continue
   824  		}
   825  
   826  		if match != -1 {
   827  			return metaImport{}, fmt.Errorf("multiple meta tags match import path %q", importPath)
   828  		}
   829  		match = i
   830  	}
   831  
   832  	if match == -1 {
   833  		return metaImport{}, errImportMismatch
   834  	}
   835  	return imports[match], nil
   836  }
   837  
   838  // expand rewrites s to replace {k} with match[k] for each key k in match.
   839  func expand(match map[string]string, s string) string {
   840  	for k, v := range match {
   841  		s = strings.Replace(s, "{"+k+"}", v, -1)
   842  	}
   843  	return s
   844  }
   845  
   846  // vcsPaths defines the meaning of import paths referring to
   847  // commonly-used VCS hosting sites (github.com/user/dir)
   848  // and import paths referring to a fully-qualified importPath
   849  // containing a VCS type (foo.com/repo.git/dir)
   850  var vcsPaths = []*vcsPath{
   851  	// Github
   852  	{
   853  		prefix: "github.com/",
   854  		re:     `^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`,
   855  		vcs:    "git",
   856  		repo:   "https://{root}",
   857  		check:  noVCSSuffix,
   858  	},
   859  
   860  	// Bitbucket
   861  	{
   862  		prefix: "bitbucket.org/",
   863  		re:     `^(?P<root>bitbucket\.org/(?P<bitname>[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`,
   864  		repo:   "https://{root}",
   865  		check:  bitbucketVCS,
   866  	},
   867  
   868  	// IBM DevOps Services (JazzHub)
   869  	{
   870  		prefix: "hub.jazz.net/git",
   871  		re:     `^(?P<root>hub.jazz.net/git/[a-z0-9]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`,
   872  		vcs:    "git",
   873  		repo:   "https://{root}",
   874  		check:  noVCSSuffix,
   875  	},
   876  
   877  	// Git at Apache
   878  	{
   879  		prefix: "git.apache.org",
   880  		re:     `^(?P<root>git.apache.org/[a-z0-9_.\-]+\.git)(/[A-Za-z0-9_.\-]+)*$`,
   881  		vcs:    "git",
   882  		repo:   "https://{root}",
   883  	},
   884  
   885  	// Git at OpenStack
   886  	{
   887  		prefix: "git.openstack.org",
   888  		re:     `^(?P<root>git\.openstack\.org/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(\.git)?(/[A-Za-z0-9_.\-]+)*$`,
   889  		vcs:    "git",
   890  		repo:   "https://{root}",
   891  	},
   892  
   893  	// General syntax for any server.
   894  	// Must be last.
   895  	{
   896  		re:   `^(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[A-Za-z0-9_.\-]+)+?)\.(?P<vcs>bzr|git|hg|svn))(/~?[A-Za-z0-9_.\-]+)*$`,
   897  		ping: true,
   898  	},
   899  }
   900  
   901  // vcsPathsAfterDynamic gives additional vcsPaths entries
   902  // to try after the dynamic HTML check.
   903  // This gives those sites a chance to introduce <meta> tags
   904  // as part of a graceful transition away from the hard-coded logic.
   905  var vcsPathsAfterDynamic = []*vcsPath{
   906  	// Launchpad. See golang.org/issue/11436.
   907  	{
   908  		prefix: "launchpad.net/",
   909  		re:     `^(?P<root>launchpad\.net/((?P<project>[A-Za-z0-9_.\-]+)(?P<series>/[A-Za-z0-9_.\-]+)?|~[A-Za-z0-9_.\-]+/(\+junk|[A-Za-z0-9_.\-]+)/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`,
   910  		vcs:    "bzr",
   911  		repo:   "https://{root}",
   912  		check:  launchpadVCS,
   913  	},
   914  }
   915  
   916  func init() {
   917  	// fill in cached regexps.
   918  	// Doing this eagerly discovers invalid regexp syntax
   919  	// without having to run a command that needs that regexp.
   920  	for _, srv := range vcsPaths {
   921  		srv.regexp = regexp.MustCompile(srv.re)
   922  	}
   923  	for _, srv := range vcsPathsAfterDynamic {
   924  		srv.regexp = regexp.MustCompile(srv.re)
   925  	}
   926  }
   927  
   928  // noVCSSuffix checks that the repository name does not
   929  // end in .foo for any version control system foo.
   930  // The usual culprit is ".git".
   931  func noVCSSuffix(match map[string]string) error {
   932  	repo := match["repo"]
   933  	for _, vcs := range vcsList {
   934  		if strings.HasSuffix(repo, "."+vcs.cmd) {
   935  			return fmt.Errorf("invalid version control suffix in %s path", match["prefix"])
   936  		}
   937  	}
   938  	return nil
   939  }
   940  
   941  // bitbucketVCS determines the version control system for a
   942  // Bitbucket repository, by using the Bitbucket API.
   943  func bitbucketVCS(match map[string]string) error {
   944  	if err := noVCSSuffix(match); err != nil {
   945  		return err
   946  	}
   947  
   948  	var resp struct {
   949  		SCM string `json:"scm"`
   950  	}
   951  	url := expand(match, "https://api.bitbucket.org/1.0/repositories/{bitname}")
   952  	data, err := web.Get(url)
   953  	if err != nil {
   954  		if httpErr, ok := err.(*web.HTTPError); ok && httpErr.StatusCode == 403 {
   955  			// this may be a private repository. If so, attempt to determine which
   956  			// VCS it uses. See issue 5375.
   957  			root := match["root"]
   958  			for _, vcs := range []string{"git", "hg"} {
   959  				if vcsByCmd(vcs).ping("https", root) == nil {
   960  					resp.SCM = vcs
   961  					break
   962  				}
   963  			}
   964  		}
   965  
   966  		if resp.SCM == "" {
   967  			return err
   968  		}
   969  	} else {
   970  		if err := json.Unmarshal(data, &resp); err != nil {
   971  			return fmt.Errorf("decoding %s: %v", url, err)
   972  		}
   973  	}
   974  
   975  	if vcsByCmd(resp.SCM) != nil {
   976  		match["vcs"] = resp.SCM
   977  		if resp.SCM == "git" {
   978  			match["repo"] += ".git"
   979  		}
   980  		return nil
   981  	}
   982  
   983  	return fmt.Errorf("unable to detect version control system for bitbucket.org/ path")
   984  }
   985  
   986  // launchpadVCS solves the ambiguity for "lp.net/project/foo". In this case,
   987  // "foo" could be a series name registered in Launchpad with its own branch,
   988  // and it could also be the name of a directory within the main project
   989  // branch one level up.
   990  func launchpadVCS(match map[string]string) error {
   991  	if match["project"] == "" || match["series"] == "" {
   992  		return nil
   993  	}
   994  	_, err := web.Get(expand(match, "https://code.launchpad.net/{project}{series}/.bzr/branch-format"))
   995  	if err != nil {
   996  		match["root"] = expand(match, "launchpad.net/{project}")
   997  		match["repo"] = expand(match, "https://{root}")
   998  	}
   999  	return nil
  1000  }