gopkg.in/tools/godep.v54@v54.0.0-20160222173036-53bf4cf4341d/vcs.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     7  	"os/exec"
     8  	"path/filepath"
     9  	"strings"
    10  
    11  	"github.com/tools/godep/Godeps/_workspace/src/golang.org/x/tools/go/vcs"
    12  )
    13  
    14  // VCS represents a version control system.
    15  type VCS struct {
    16  	vcs *vcs.Cmd
    17  
    18  	IdentifyCmd string
    19  	DescribeCmd string
    20  	DiffCmd     string
    21  	ListCmd     string
    22  	RootCmd     string
    23  
    24  	// run in sandbox repos
    25  	ExistsCmd string
    26  }
    27  
    28  var vcsBzr = &VCS{
    29  	vcs: vcs.ByCmd("bzr"),
    30  
    31  	IdentifyCmd: "version-info --custom --template {revision_id}",
    32  	DescribeCmd: "revno", // TODO(kr): find tag names if possible
    33  	DiffCmd:     "diff -r {rev}",
    34  	ListCmd:     "ls --from-root -R",
    35  	RootCmd:     "root",
    36  }
    37  
    38  var vcsGit = &VCS{
    39  	vcs: vcs.ByCmd("git"),
    40  
    41  	IdentifyCmd: "rev-parse HEAD",
    42  	DescribeCmd: "describe --tags",
    43  	DiffCmd:     "diff {rev}",
    44  	ListCmd:     "ls-files --full-name",
    45  	RootCmd:     "rev-parse --show-toplevel",
    46  
    47  	ExistsCmd: "cat-file -e {rev}",
    48  }
    49  
    50  var vcsHg = &VCS{
    51  	vcs: vcs.ByCmd("hg"),
    52  
    53  	IdentifyCmd: "parents --template '{node}'",
    54  	DescribeCmd: "log -r . --template {latesttag}-{latesttagdistance}",
    55  	DiffCmd:     "diff -r {rev}",
    56  	ListCmd:     "status --all --no-status",
    57  	RootCmd:     "root",
    58  
    59  	ExistsCmd: "cat -r {rev} .",
    60  }
    61  
    62  var cmd = map[*vcs.Cmd]*VCS{
    63  	vcsBzr.vcs: vcsBzr,
    64  	vcsGit.vcs: vcsGit,
    65  	vcsHg.vcs:  vcsHg,
    66  }
    67  
    68  // VCSFromDir returns a VCS value from a directory.
    69  func VCSFromDir(dir, srcRoot string) (*VCS, string, error) {
    70  	vcscmd, reporoot, err := vcs.FromDir(dir, srcRoot)
    71  	if err != nil {
    72  		return nil, "", fmt.Errorf("error while inspecting %q: %v", dir, err)
    73  	}
    74  	vcsext := cmd[vcscmd]
    75  	if vcsext == nil {
    76  		return nil, "", fmt.Errorf("%s is unsupported: %s", vcscmd.Name, dir)
    77  	}
    78  	return vcsext, reporoot, nil
    79  }
    80  
    81  // VCSForImportPath returns a VCS value for an import path.
    82  func VCSForImportPath(importPath string) (*VCS, error) {
    83  	rr, err := vcs.RepoRootForImportPath(importPath, debug)
    84  	if err != nil {
    85  		return nil, err
    86  	}
    87  	vcs := cmd[rr.VCS]
    88  	if vcs == nil {
    89  		return nil, fmt.Errorf("%s is unsupported: %s", rr.VCS.Name, importPath)
    90  	}
    91  	return vcs, nil
    92  }
    93  
    94  func (v *VCS) identify(dir string) (string, error) {
    95  	out, err := v.runOutput(dir, v.IdentifyCmd)
    96  	return string(bytes.TrimSpace(out)), err
    97  }
    98  
    99  func (v *VCS) root(dir string) (string, error) {
   100  	out, err := v.runOutput(dir, v.RootCmd)
   101  	return filepath.Clean(string(bytes.TrimSpace(out))), err
   102  }
   103  
   104  func (v *VCS) describe(dir, rev string) string {
   105  	out, err := v.runOutputVerboseOnly(dir, v.DescribeCmd, "rev", rev)
   106  	if err != nil {
   107  		return ""
   108  	}
   109  	return string(bytes.TrimSpace(out))
   110  }
   111  
   112  func (v *VCS) isDirty(dir, rev string) bool {
   113  	out, err := v.runOutput(dir, v.DiffCmd, "rev", rev)
   114  	return err != nil || len(out) != 0
   115  }
   116  
   117  type vcsFiles map[string]bool
   118  
   119  func (vf vcsFiles) Contains(path string) bool {
   120  	// Fast path, we have the path
   121  	if vf[path] {
   122  		return true
   123  	}
   124  
   125  	// Slow path for case insensitive filesystems
   126  	// See #310
   127  	for f := range vf {
   128  		if strings.EqualFold(f, path) {
   129  			return true
   130  		}
   131  		// git's root command (maybe other vcs as well) resolve symlinks, so try that too
   132  		// FIXME: rev-parse --show-cdup + extra logic will fix this for git but also need to validate the other vcs commands. This is maybe temporary.
   133  		p, err := filepath.EvalSymlinks(path)
   134  		if err != nil {
   135  			return false
   136  		}
   137  		if strings.EqualFold(f, p) {
   138  			return true
   139  		}
   140  	}
   141  
   142  	// No matches by either method
   143  	return false
   144  }
   145  
   146  // listFiles tracked by the VCS in the repo that contains dir, converted to absolute path.
   147  func (v *VCS) listFiles(dir string) vcsFiles {
   148  	root, err := v.root(dir)
   149  	debugln("vcs root", root)
   150  	if err != nil {
   151  		return nil
   152  	}
   153  	out, err := v.runOutput(dir, v.ListCmd)
   154  	if err != nil {
   155  		return nil
   156  	}
   157  	files := make(vcsFiles)
   158  	for _, file := range bytes.Split(out, []byte{'\n'}) {
   159  		if len(file) > 0 {
   160  			path, err := filepath.Abs(filepath.Join(string(root), string(file)))
   161  			if err != nil {
   162  				panic(err) // this should not happen
   163  			}
   164  
   165  			if filepath.Dir(path) == dir {
   166  				files[path] = true
   167  			}
   168  		}
   169  	}
   170  	return files
   171  }
   172  
   173  func (v *VCS) exists(dir, rev string) bool {
   174  	err := v.runVerboseOnly(dir, v.ExistsCmd, "rev", rev)
   175  	return err == nil
   176  }
   177  
   178  // RevSync checks out the revision given by rev in dir.
   179  // The dir must exist and rev must be a valid revision.
   180  func (v *VCS) RevSync(dir, rev string) error {
   181  	return v.run(dir, v.vcs.TagSyncCmd, "tag", rev)
   182  }
   183  
   184  // run runs the command line cmd in the given directory.
   185  // keyval is a list of key, value pairs.  run expands
   186  // instances of {key} in cmd into value, but only after
   187  // splitting cmd into individual arguments.
   188  // If an error occurs, run prints the command line and the
   189  // command's combined stdout+stderr to standard error.
   190  // Otherwise run discards the command's output.
   191  func (v *VCS) run(dir string, cmdline string, kv ...string) error {
   192  	_, err := v.run1(dir, cmdline, kv, true)
   193  	return err
   194  }
   195  
   196  // runVerboseOnly is like run but only generates error output to standard error in verbose mode.
   197  func (v *VCS) runVerboseOnly(dir string, cmdline string, kv ...string) error {
   198  	_, err := v.run1(dir, cmdline, kv, false)
   199  	return err
   200  }
   201  
   202  // runOutput is like run but returns the output of the command.
   203  func (v *VCS) runOutput(dir string, cmdline string, kv ...string) ([]byte, error) {
   204  	return v.run1(dir, cmdline, kv, true)
   205  }
   206  
   207  // runOutputVerboseOnly is like runOutput but only generates error output to standard error in verbose mode.
   208  func (v *VCS) runOutputVerboseOnly(dir string, cmdline string, kv ...string) ([]byte, error) {
   209  	return v.run1(dir, cmdline, kv, false)
   210  }
   211  
   212  // run1 is the generalized implementation of run and runOutput.
   213  func (v *VCS) run1(dir string, cmdline string, kv []string, verbose bool) ([]byte, error) {
   214  	m := make(map[string]string)
   215  	for i := 0; i < len(kv); i += 2 {
   216  		m[kv[i]] = kv[i+1]
   217  	}
   218  	args := strings.Fields(cmdline)
   219  	for i, arg := range args {
   220  		args[i] = expand(m, arg)
   221  	}
   222  
   223  	_, err := exec.LookPath(v.vcs.Cmd)
   224  	if err != nil {
   225  		fmt.Fprintf(os.Stderr, "godep: missing %s command.\n", v.vcs.Name)
   226  		return nil, err
   227  	}
   228  
   229  	cmd := exec.Command(v.vcs.Cmd, args...)
   230  	cmd.Dir = dir
   231  	var buf bytes.Buffer
   232  	cmd.Stdout = &buf
   233  	cmd.Stderr = &buf
   234  	err = cmd.Run()
   235  	out := buf.Bytes()
   236  	if err != nil {
   237  		if verbose {
   238  			fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.vcs.Cmd, strings.Join(args, " "))
   239  			os.Stderr.Write(out)
   240  		}
   241  		return nil, err
   242  	}
   243  	return out, nil
   244  }
   245  
   246  func expand(m map[string]string, s string) string {
   247  	for k, v := range m {
   248  		s = strings.Replace(s, "{"+k+"}", v, -1)
   249  	}
   250  	return s
   251  }
   252  
   253  // Mercurial has no command equivalent to git remote add.
   254  // We handle it as a special case in process.
   255  func hgLink(dir, remote, url string) error {
   256  	hgdir := filepath.Join(dir, ".hg")
   257  	if err := os.MkdirAll(hgdir, 0777); err != nil {
   258  		return err
   259  	}
   260  	path := filepath.Join(hgdir, "hgrc")
   261  	f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
   262  	if err != nil {
   263  		return err
   264  	}
   265  	fmt.Fprintf(f, "[paths]\n%s = %s\n", remote, url)
   266  	return f.Close()
   267  }