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