github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/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  	"log"
    13  	"os"
    14  	"os/exec"
    15  	"path/filepath"
    16  	"regexp"
    17  	"strings"
    18  )
    19  
    20  // A vcsCmd describes how to use a version control system
    21  // like Mercurial, Git, or Subversion.
    22  type vcsCmd struct {
    23  	name string
    24  	cmd  string // name of binary to invoke command
    25  
    26  	createCmd   string // command to download a fresh copy of a repository
    27  	downloadCmd string // command to download updates into an existing repository
    28  
    29  	tagCmd         []tagCmd // commands to list tags
    30  	tagLookupCmd   []tagCmd // commands to lookup tags before running tagSyncCmd
    31  	tagSyncCmd     string   // command to sync to specific tag
    32  	tagSyncDefault string   // command to sync to default tag
    33  
    34  	scheme  []string
    35  	pingCmd string
    36  }
    37  
    38  // A tagCmd describes a command to list available tags
    39  // that can be passed to tagSyncCmd.
    40  type tagCmd struct {
    41  	cmd     string // command to list tags
    42  	pattern string // regexp to extract tags from list
    43  }
    44  
    45  // vcsList lists the known version control systems
    46  var vcsList = []*vcsCmd{
    47  	vcsHg,
    48  	vcsGit,
    49  	vcsSvn,
    50  	vcsBzr,
    51  }
    52  
    53  // vcsByCmd returns the version control system for the given
    54  // command name (hg, git, svn, bzr).
    55  func vcsByCmd(cmd string) *vcsCmd {
    56  	for _, vcs := range vcsList {
    57  		if vcs.cmd == cmd {
    58  			return vcs
    59  		}
    60  	}
    61  	return nil
    62  }
    63  
    64  // vcsHg describes how to use Mercurial.
    65  var vcsHg = &vcsCmd{
    66  	name: "Mercurial",
    67  	cmd:  "hg",
    68  
    69  	createCmd:   "clone -U {repo} {dir}",
    70  	downloadCmd: "pull",
    71  
    72  	// We allow both tag and branch names as 'tags'
    73  	// for selecting a version.  This lets people have
    74  	// a go.release.r60 branch and a go1 branch
    75  	// and make changes in both, without constantly
    76  	// editing .hgtags.
    77  	tagCmd: []tagCmd{
    78  		{"tags", `^(\S+)`},
    79  		{"branches", `^(\S+)`},
    80  	},
    81  	tagSyncCmd:     "update -r {tag}",
    82  	tagSyncDefault: "update default",
    83  
    84  	scheme:  []string{"https", "http", "ssh"},
    85  	pingCmd: "identify {scheme}://{repo}",
    86  }
    87  
    88  // vcsGit describes how to use Git.
    89  var vcsGit = &vcsCmd{
    90  	name: "Git",
    91  	cmd:  "git",
    92  
    93  	createCmd:   "clone {repo} {dir}",
    94  	downloadCmd: "pull --ff-only",
    95  
    96  	tagCmd: []tagCmd{
    97  		// tags/xxx matches a git tag named xxx
    98  		// origin/xxx matches a git branch named xxx on the default remote repository
    99  		{"show-ref", `(?:tags|origin)/(\S+)$`},
   100  	},
   101  	tagLookupCmd: []tagCmd{
   102  		{"show-ref tags/{tag} origin/{tag}", `((?:tags|origin)/\S+)$`},
   103  	},
   104  	tagSyncCmd:     "checkout {tag}",
   105  	tagSyncDefault: "checkout master",
   106  
   107  	scheme:  []string{"git", "https", "http", "git+ssh"},
   108  	pingCmd: "ls-remote {scheme}://{repo}",
   109  }
   110  
   111  // vcsBzr describes how to use Bazaar.
   112  var vcsBzr = &vcsCmd{
   113  	name: "Bazaar",
   114  	cmd:  "bzr",
   115  
   116  	createCmd: "branch {repo} {dir}",
   117  
   118  	// Without --overwrite bzr will not pull tags that changed.
   119  	// Replace by --overwrite-tags after http://pad.lv/681792 goes in.
   120  	downloadCmd: "pull --overwrite",
   121  
   122  	tagCmd:         []tagCmd{{"tags", `^(\S+)`}},
   123  	tagSyncCmd:     "update -r {tag}",
   124  	tagSyncDefault: "update -r revno:-1",
   125  
   126  	scheme:  []string{"https", "http", "bzr", "bzr+ssh"},
   127  	pingCmd: "info {scheme}://{repo}",
   128  }
   129  
   130  // vcsSvn describes how to use Subversion.
   131  var vcsSvn = &vcsCmd{
   132  	name: "Subversion",
   133  	cmd:  "svn",
   134  
   135  	createCmd:   "checkout {repo} {dir}",
   136  	downloadCmd: "update",
   137  
   138  	// There is no tag command in subversion.
   139  	// The branch information is all in the path names.
   140  
   141  	scheme:  []string{"https", "http", "svn", "svn+ssh"},
   142  	pingCmd: "info {scheme}://{repo}",
   143  }
   144  
   145  func (v *vcsCmd) String() string {
   146  	return v.name
   147  }
   148  
   149  // run runs the command line cmd in the given directory.
   150  // keyval is a list of key, value pairs.  run expands
   151  // instances of {key} in cmd into value, but only after
   152  // splitting cmd into individual arguments.
   153  // If an error occurs, run prints the command line and the
   154  // command's combined stdout+stderr to standard error.
   155  // Otherwise run discards the command's output.
   156  func (v *vcsCmd) run(dir string, cmd string, keyval ...string) error {
   157  	_, err := v.run1(dir, cmd, keyval, true)
   158  	return err
   159  }
   160  
   161  // runVerboseOnly is like run but only generates error output to standard error in verbose mode.
   162  func (v *vcsCmd) runVerboseOnly(dir string, cmd string, keyval ...string) error {
   163  	_, err := v.run1(dir, cmd, keyval, false)
   164  	return err
   165  }
   166  
   167  // runOutput is like run but returns the output of the command.
   168  func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {
   169  	return v.run1(dir, cmd, keyval, true)
   170  }
   171  
   172  // run1 is the generalized implementation of run and runOutput.
   173  func (v *vcsCmd) run1(dir string, cmdline string, keyval []string, verbose bool) ([]byte, error) {
   174  	m := make(map[string]string)
   175  	for i := 0; i < len(keyval); i += 2 {
   176  		m[keyval[i]] = keyval[i+1]
   177  	}
   178  	args := strings.Fields(cmdline)
   179  	for i, arg := range args {
   180  		args[i] = expand(m, arg)
   181  	}
   182  
   183  	_, err := exec.LookPath(v.cmd)
   184  	if err != nil {
   185  		fmt.Fprintf(os.Stderr,
   186  			"go: missing %s command. See http://golang.org/s/gogetcmd\n",
   187  			v.name)
   188  		return nil, err
   189  	}
   190  
   191  	cmd := exec.Command(v.cmd, args...)
   192  	cmd.Dir = dir
   193  	cmd.Env = envForDir(cmd.Dir)
   194  	if buildX {
   195  		fmt.Printf("cd %s\n", dir)
   196  		fmt.Printf("%s %s\n", v.cmd, strings.Join(args, " "))
   197  	}
   198  	var buf bytes.Buffer
   199  	cmd.Stdout = &buf
   200  	cmd.Stderr = &buf
   201  	err = cmd.Run()
   202  	out := buf.Bytes()
   203  	if err != nil {
   204  		if verbose || buildV {
   205  			fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.cmd, strings.Join(args, " "))
   206  			os.Stderr.Write(out)
   207  		}
   208  		return nil, err
   209  	}
   210  	return out, nil
   211  }
   212  
   213  // ping pings to determine scheme to use.
   214  func (v *vcsCmd) ping(scheme, repo string) error {
   215  	return v.runVerboseOnly(".", v.pingCmd, "scheme", scheme, "repo", repo)
   216  }
   217  
   218  // create creates a new copy of repo in dir.
   219  // The parent of dir must exist; dir must not.
   220  func (v *vcsCmd) create(dir, repo string) error {
   221  	return v.run(".", v.createCmd, "dir", dir, "repo", repo)
   222  }
   223  
   224  // download downloads any new changes for the repo in dir.
   225  func (v *vcsCmd) download(dir string) error {
   226  	if err := v.fixDetachedHead(dir); err != nil {
   227  		return err
   228  	}
   229  	return v.run(dir, v.downloadCmd)
   230  }
   231  
   232  // fixDetachedHead switches a Git repository in dir from a detached head to the master branch.
   233  // Go versions before 1.2 downloaded Git repositories in an unfortunate way
   234  // that resulted in the working tree state being on a detached head.
   235  // That meant the repository was not usable for normal Git operations.
   236  // Go 1.2 fixed that, but we can't pull into a detached head, so if this is
   237  // a Git repository we check for being on a detached head and switch to the
   238  // real branch, almost always called "master".
   239  // TODO(dsymonds): Consider removing this for Go 1.3.
   240  func (v *vcsCmd) fixDetachedHead(dir string) error {
   241  	if v != vcsGit {
   242  		return nil
   243  	}
   244  
   245  	// "git symbolic-ref HEAD" succeeds iff we are not on a detached head.
   246  	if err := v.runVerboseOnly(dir, "symbolic-ref HEAD"); err == nil {
   247  		// not on a detached head
   248  		return nil
   249  	}
   250  	if buildV {
   251  		log.Printf("%s on detached head; repairing", dir)
   252  	}
   253  	return v.run(dir, "checkout master")
   254  }
   255  
   256  // tags returns the list of available tags for the repo in dir.
   257  func (v *vcsCmd) tags(dir string) ([]string, error) {
   258  	var tags []string
   259  	for _, tc := range v.tagCmd {
   260  		out, err := v.runOutput(dir, tc.cmd)
   261  		if err != nil {
   262  			return nil, err
   263  		}
   264  		re := regexp.MustCompile(`(?m-s)` + tc.pattern)
   265  		for _, m := range re.FindAllStringSubmatch(string(out), -1) {
   266  			tags = append(tags, m[1])
   267  		}
   268  	}
   269  	return tags, nil
   270  }
   271  
   272  // tagSync syncs the repo in dir to the named tag,
   273  // which either is a tag returned by tags or is v.tagDefault.
   274  func (v *vcsCmd) tagSync(dir, tag string) error {
   275  	if v.tagSyncCmd == "" {
   276  		return nil
   277  	}
   278  	if tag != "" {
   279  		for _, tc := range v.tagLookupCmd {
   280  			out, err := v.runOutput(dir, tc.cmd, "tag", tag)
   281  			if err != nil {
   282  				return err
   283  			}
   284  			re := regexp.MustCompile(`(?m-s)` + tc.pattern)
   285  			m := re.FindStringSubmatch(string(out))
   286  			if len(m) > 1 {
   287  				tag = m[1]
   288  				break
   289  			}
   290  		}
   291  	}
   292  	if tag == "" && v.tagSyncDefault != "" {
   293  		return v.run(dir, v.tagSyncDefault)
   294  	}
   295  	return v.run(dir, v.tagSyncCmd, "tag", tag)
   296  }
   297  
   298  // A vcsPath describes how to convert an import path into a
   299  // version control system and repository name.
   300  type vcsPath struct {
   301  	prefix string                              // prefix this description applies to
   302  	re     string                              // pattern for import path
   303  	repo   string                              // repository to use (expand with match of re)
   304  	vcs    string                              // version control system to use (expand with match of re)
   305  	check  func(match map[string]string) error // additional checks
   306  	ping   bool                                // ping for scheme to use to download repo
   307  
   308  	regexp *regexp.Regexp // cached compiled form of re
   309  }
   310  
   311  // vcsForDir inspects dir and its parents to determine the
   312  // version control system and code repository to use.
   313  // On return, root is the import path
   314  // corresponding to the root of the repository
   315  // (thus root is a prefix of importPath).
   316  func vcsForDir(p *Package) (vcs *vcsCmd, root string, err error) {
   317  	// Clean and double-check that dir is in (a subdirectory of) srcRoot.
   318  	dir := filepath.Clean(p.Dir)
   319  	srcRoot := filepath.Clean(p.build.SrcRoot)
   320  	if len(dir) <= len(srcRoot) || dir[len(srcRoot)] != filepath.Separator {
   321  		return nil, "", fmt.Errorf("directory %q is outside source root %q", dir, srcRoot)
   322  	}
   323  
   324  	origDir := dir
   325  	for len(dir) > len(srcRoot) {
   326  		for _, vcs := range vcsList {
   327  			if fi, err := os.Stat(filepath.Join(dir, "."+vcs.cmd)); err == nil && fi.IsDir() {
   328  				return vcs, dir[len(srcRoot)+1:], nil
   329  			}
   330  		}
   331  
   332  		// Move to parent.
   333  		ndir := filepath.Dir(dir)
   334  		if len(ndir) >= len(dir) {
   335  			// Shouldn't happen, but just in case, stop.
   336  			break
   337  		}
   338  		dir = ndir
   339  	}
   340  
   341  	return nil, "", fmt.Errorf("directory %q is not using a known version control system", origDir)
   342  }
   343  
   344  // repoRoot represents a version control system, a repo, and a root of
   345  // where to put it on disk.
   346  type repoRoot struct {
   347  	vcs *vcsCmd
   348  
   349  	// repo is the repository URL, including scheme
   350  	repo string
   351  
   352  	// root is the import path corresponding to the root of the
   353  	// repository
   354  	root string
   355  }
   356  
   357  // repoRootForImportPath analyzes importPath to determine the
   358  // version control system, and code repository to use.
   359  func repoRootForImportPath(importPath string) (*repoRoot, error) {
   360  	rr, err := repoRootForImportPathStatic(importPath, "")
   361  	if err == errUnknownSite {
   362  		rr, err = repoRootForImportDynamic(importPath)
   363  
   364  		// repoRootForImportDynamic returns error detail
   365  		// that is irrelevant if the user didn't intend to use a
   366  		// dynamic import in the first place.
   367  		// Squelch it.
   368  		if err != nil {
   369  			if buildV {
   370  				log.Printf("import %q: %v", importPath, err)
   371  			}
   372  			err = fmt.Errorf("unrecognized import path %q", importPath)
   373  		}
   374  	}
   375  
   376  	if err == nil && strings.Contains(importPath, "...") && strings.Contains(rr.root, "...") {
   377  		// Do not allow wildcards in the repo root.
   378  		rr = nil
   379  		err = fmt.Errorf("cannot expand ... in %q", importPath)
   380  	}
   381  	return rr, err
   382  }
   383  
   384  var errUnknownSite = errors.New("dynamic lookup required to find mapping")
   385  
   386  // repoRootForImportPathStatic attempts to map importPath to a
   387  // repoRoot using the commonly-used VCS hosting sites in vcsPaths
   388  // (github.com/user/dir), or from a fully-qualified importPath already
   389  // containing its VCS type (foo.com/repo.git/dir)
   390  //
   391  // If scheme is non-empty, that scheme is forced.
   392  func repoRootForImportPathStatic(importPath, scheme string) (*repoRoot, error) {
   393  	if strings.Contains(importPath, "://") {
   394  		return nil, fmt.Errorf("invalid import path %q", importPath)
   395  	}
   396  	for _, srv := range vcsPaths {
   397  		if !strings.HasPrefix(importPath, srv.prefix) {
   398  			continue
   399  		}
   400  		m := srv.regexp.FindStringSubmatch(importPath)
   401  		if m == nil {
   402  			if srv.prefix != "" {
   403  				return nil, fmt.Errorf("invalid %s import path %q", srv.prefix, importPath)
   404  			}
   405  			continue
   406  		}
   407  
   408  		// Build map of named subexpression matches for expand.
   409  		match := map[string]string{
   410  			"prefix": srv.prefix,
   411  			"import": importPath,
   412  		}
   413  		for i, name := range srv.regexp.SubexpNames() {
   414  			if name != "" && match[name] == "" {
   415  				match[name] = m[i]
   416  			}
   417  		}
   418  		if srv.vcs != "" {
   419  			match["vcs"] = expand(match, srv.vcs)
   420  		}
   421  		if srv.repo != "" {
   422  			match["repo"] = expand(match, srv.repo)
   423  		}
   424  		if srv.check != nil {
   425  			if err := srv.check(match); err != nil {
   426  				return nil, err
   427  			}
   428  		}
   429  		vcs := vcsByCmd(match["vcs"])
   430  		if vcs == nil {
   431  			return nil, fmt.Errorf("unknown version control system %q", match["vcs"])
   432  		}
   433  		if srv.ping {
   434  			if scheme != "" {
   435  				match["repo"] = scheme + "://" + match["repo"]
   436  			} else {
   437  				for _, scheme := range vcs.scheme {
   438  					if vcs.ping(scheme, match["repo"]) == nil {
   439  						match["repo"] = scheme + "://" + match["repo"]
   440  						break
   441  					}
   442  				}
   443  			}
   444  		}
   445  		rr := &repoRoot{
   446  			vcs:  vcs,
   447  			repo: match["repo"],
   448  			root: match["root"],
   449  		}
   450  		return rr, nil
   451  	}
   452  	return nil, errUnknownSite
   453  }
   454  
   455  // repoRootForImportDynamic finds a *repoRoot for a custom domain that's not
   456  // statically known by repoRootForImportPathStatic.
   457  //
   458  // This handles "vanity import paths" like "name.tld/pkg/foo".
   459  func repoRootForImportDynamic(importPath string) (*repoRoot, error) {
   460  	slash := strings.Index(importPath, "/")
   461  	if slash < 0 {
   462  		return nil, errors.New("import path doesn't contain a slash")
   463  	}
   464  	host := importPath[:slash]
   465  	if !strings.Contains(host, ".") {
   466  		return nil, errors.New("import path doesn't contain a hostname")
   467  	}
   468  	urlStr, body, err := httpsOrHTTP(importPath)
   469  	if err != nil {
   470  		return nil, fmt.Errorf("http/https fetch: %v", err)
   471  	}
   472  	defer body.Close()
   473  	imports, err := parseMetaGoImports(body)
   474  	if err != nil {
   475  		return nil, fmt.Errorf("parsing %s: %v", importPath, err)
   476  	}
   477  	metaImport, err := matchGoImport(imports, importPath)
   478  	if err != nil {
   479  		if err != errNoMatch {
   480  			return nil, fmt.Errorf("parse %s: %v", urlStr, err)
   481  		}
   482  		return nil, fmt.Errorf("parse %s: no go-import meta tags", urlStr)
   483  	}
   484  	if buildV {
   485  		log.Printf("get %q: found meta tag %#v at %s", importPath, metaImport, urlStr)
   486  	}
   487  	// If the import was "uni.edu/bob/project", which said the
   488  	// prefix was "uni.edu" and the RepoRoot was "evilroot.com",
   489  	// make sure we don't trust Bob and check out evilroot.com to
   490  	// "uni.edu" yet (possibly overwriting/preempting another
   491  	// non-evil student).  Instead, first verify the root and see
   492  	// if it matches Bob's claim.
   493  	if metaImport.Prefix != importPath {
   494  		if buildV {
   495  			log.Printf("get %q: verifying non-authoritative meta tag", importPath)
   496  		}
   497  		urlStr0 := urlStr
   498  		urlStr, body, err = httpsOrHTTP(metaImport.Prefix)
   499  		if err != nil {
   500  			return nil, fmt.Errorf("fetch %s: %v", urlStr, err)
   501  		}
   502  		imports, err := parseMetaGoImports(body)
   503  		if err != nil {
   504  			return nil, fmt.Errorf("parsing %s: %v", importPath, err)
   505  		}
   506  		if len(imports) == 0 {
   507  			return nil, fmt.Errorf("fetch %s: no go-import meta tag", urlStr)
   508  		}
   509  		metaImport2, err := matchGoImport(imports, importPath)
   510  		if err != nil || metaImport != metaImport2 {
   511  			return nil, fmt.Errorf("%s and %s disagree about go-import for %s", urlStr0, urlStr, metaImport.Prefix)
   512  		}
   513  	}
   514  
   515  	if !strings.Contains(metaImport.RepoRoot, "://") {
   516  		return nil, fmt.Errorf("%s: invalid repo root %q; no scheme", urlStr, metaImport.RepoRoot)
   517  	}
   518  	rr := &repoRoot{
   519  		vcs:  vcsByCmd(metaImport.VCS),
   520  		repo: metaImport.RepoRoot,
   521  		root: metaImport.Prefix,
   522  	}
   523  	if rr.vcs == nil {
   524  		return nil, fmt.Errorf("%s: unknown vcs %q", urlStr, metaImport.VCS)
   525  	}
   526  	return rr, nil
   527  }
   528  
   529  // metaImport represents the parsed <meta name="go-import"
   530  // content="prefix vcs reporoot" /> tags from HTML files.
   531  type metaImport struct {
   532  	Prefix, VCS, RepoRoot string
   533  }
   534  
   535  // errNoMatch is returned from matchGoImport when there's no applicable match.
   536  var errNoMatch = errors.New("no import match")
   537  
   538  // matchGoImport returns the metaImport from imports matching importPath.
   539  // An error is returned if there are multiple matches.
   540  // errNoMatch is returned if none match.
   541  func matchGoImport(imports []metaImport, importPath string) (_ metaImport, err error) {
   542  	match := -1
   543  	for i, im := range imports {
   544  		if !strings.HasPrefix(importPath, im.Prefix) {
   545  			continue
   546  		}
   547  		if match != -1 {
   548  			err = fmt.Errorf("multiple meta tags match import path %q", importPath)
   549  			return
   550  		}
   551  		match = i
   552  	}
   553  	if match == -1 {
   554  		err = errNoMatch
   555  		return
   556  	}
   557  	return imports[match], nil
   558  }
   559  
   560  // expand rewrites s to replace {k} with match[k] for each key k in match.
   561  func expand(match map[string]string, s string) string {
   562  	for k, v := range match {
   563  		s = strings.Replace(s, "{"+k+"}", v, -1)
   564  	}
   565  	return s
   566  }
   567  
   568  // vcsPaths lists the known vcs paths.
   569  var vcsPaths = []*vcsPath{
   570  	// Google Code - new syntax
   571  	{
   572  		prefix: "code.google.com/",
   573  		re:     `^(?P<root>code\.google\.com/p/(?P<project>[a-z0-9\-]+)(\.(?P<subrepo>[a-z0-9\-]+))?)(/[A-Za-z0-9_.\-]+)*$`,
   574  		repo:   "https://{root}",
   575  		check:  googleCodeVCS,
   576  	},
   577  
   578  	// Google Code - old syntax
   579  	{
   580  		re:    `^(?P<project>[a-z0-9_\-.]+)\.googlecode\.com/(git|hg|svn)(?P<path>/.*)?$`,
   581  		check: oldGoogleCode,
   582  	},
   583  
   584  	// Github
   585  	{
   586  		prefix: "github.com/",
   587  		re:     `^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`,
   588  		vcs:    "git",
   589  		repo:   "https://{root}",
   590  		check:  noVCSSuffix,
   591  	},
   592  
   593  	// Bitbucket
   594  	{
   595  		prefix: "bitbucket.org/",
   596  		re:     `^(?P<root>bitbucket\.org/(?P<bitname>[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`,
   597  		repo:   "https://{root}",
   598  		check:  bitbucketVCS,
   599  	},
   600  
   601  	// Launchpad
   602  	{
   603  		prefix: "launchpad.net/",
   604  		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_.\-]+)*$`,
   605  		vcs:    "bzr",
   606  		repo:   "https://{root}",
   607  		check:  launchpadVCS,
   608  	},
   609  
   610  	// General syntax for any server.
   611  	{
   612  		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_.\-]+)*$`,
   613  		ping: true,
   614  	},
   615  }
   616  
   617  func init() {
   618  	// fill in cached regexps.
   619  	// Doing this eagerly discovers invalid regexp syntax
   620  	// without having to run a command that needs that regexp.
   621  	for _, srv := range vcsPaths {
   622  		srv.regexp = regexp.MustCompile(srv.re)
   623  	}
   624  }
   625  
   626  // noVCSSuffix checks that the repository name does not
   627  // end in .foo for any version control system foo.
   628  // The usual culprit is ".git".
   629  func noVCSSuffix(match map[string]string) error {
   630  	repo := match["repo"]
   631  	for _, vcs := range vcsList {
   632  		if strings.HasSuffix(repo, "."+vcs.cmd) {
   633  			return fmt.Errorf("invalid version control suffix in %s path", match["prefix"])
   634  		}
   635  	}
   636  	return nil
   637  }
   638  
   639  var googleCheckout = regexp.MustCompile(`id="checkoutcmd">(hg|git|svn)`)
   640  
   641  // googleCodeVCS determines the version control system for
   642  // a code.google.com repository, by scraping the project's
   643  // /source/checkout page.
   644  func googleCodeVCS(match map[string]string) error {
   645  	if err := noVCSSuffix(match); err != nil {
   646  		return err
   647  	}
   648  	data, err := httpGET(expand(match, "https://code.google.com/p/{project}/source/checkout?repo={subrepo}"))
   649  	if err != nil {
   650  		return err
   651  	}
   652  
   653  	if m := googleCheckout.FindSubmatch(data); m != nil {
   654  		if vcs := vcsByCmd(string(m[1])); vcs != nil {
   655  			// Subversion requires the old URLs.
   656  			// TODO: Test.
   657  			if vcs == vcsSvn {
   658  				if match["subrepo"] != "" {
   659  					return fmt.Errorf("sub-repositories not supported in Google Code Subversion projects")
   660  				}
   661  				match["repo"] = expand(match, "https://{project}.googlecode.com/svn")
   662  			}
   663  			match["vcs"] = vcs.cmd
   664  			return nil
   665  		}
   666  	}
   667  
   668  	return fmt.Errorf("unable to detect version control system for code.google.com/ path")
   669  }
   670  
   671  // oldGoogleCode is invoked for old-style foo.googlecode.com paths.
   672  // It prints an error giving the equivalent new path.
   673  func oldGoogleCode(match map[string]string) error {
   674  	return fmt.Errorf("invalid Google Code import path: use %s instead",
   675  		expand(match, "code.google.com/p/{project}{path}"))
   676  }
   677  
   678  // bitbucketVCS determines the version control system for a
   679  // Bitbucket repository, by using the Bitbucket API.
   680  func bitbucketVCS(match map[string]string) error {
   681  	if err := noVCSSuffix(match); err != nil {
   682  		return err
   683  	}
   684  
   685  	var resp struct {
   686  		SCM string `json:"scm"`
   687  	}
   688  	url := expand(match, "https://api.bitbucket.org/1.0/repositories/{bitname}")
   689  	data, err := httpGET(url)
   690  	if err != nil {
   691  		return err
   692  	}
   693  	if err := json.Unmarshal(data, &resp); err != nil {
   694  		return fmt.Errorf("decoding %s: %v", url, err)
   695  	}
   696  
   697  	if vcsByCmd(resp.SCM) != nil {
   698  		match["vcs"] = resp.SCM
   699  		if resp.SCM == "git" {
   700  			match["repo"] += ".git"
   701  		}
   702  		return nil
   703  	}
   704  
   705  	return fmt.Errorf("unable to detect version control system for bitbucket.org/ path")
   706  }
   707  
   708  // launchpadVCS solves the ambiguity for "lp.net/project/foo". In this case,
   709  // "foo" could be a series name registered in Launchpad with its own branch,
   710  // and it could also be the name of a directory within the main project
   711  // branch one level up.
   712  func launchpadVCS(match map[string]string) error {
   713  	if match["project"] == "" || match["series"] == "" {
   714  		return nil
   715  	}
   716  	_, err := httpGET(expand(match, "https://code.launchpad.net/{project}{series}/.bzr/branch-format"))
   717  	if err != nil {
   718  		match["root"] = expand(match, "launchpad.net/{project}")
   719  		match["repo"] = expand(match, "https://{root}")
   720  	}
   721  	return nil
   722  }