gopkg.in/tools/godep.v21@v21.0.0-20151104013723-2cf1d6e3f557/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: "identify --id --debug",
    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, verbose)
    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 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  	}
   132  
   133  	// No matches by either method
   134  	return false
   135  }
   136  
   137  // listFiles tracked by the VCS in the repo that contains dir, converted to absolute path.
   138  func (v *VCS) listFiles(dir string) vcsFiles {
   139  	root, err := v.root(dir)
   140  	if err != nil {
   141  		return nil
   142  	}
   143  	out, err := v.runOutput(dir, v.ListCmd)
   144  	if err != nil {
   145  		return nil
   146  	}
   147  	files := make(vcsFiles)
   148  	for _, file := range bytes.Split(out, []byte{'\n'}) {
   149  		if len(file) > 0 {
   150  			path, err := filepath.Abs(filepath.Join(string(root), string(file)))
   151  			if err != nil {
   152  				panic(err) // this should not happen
   153  			}
   154  			files[path] = true
   155  		}
   156  	}
   157  	return files
   158  }
   159  
   160  func (v *VCS) exists(dir, rev string) bool {
   161  	err := v.runVerboseOnly(dir, v.ExistsCmd, "rev", rev)
   162  	return err == nil
   163  }
   164  
   165  // RevSync checks out the revision given by rev in dir.
   166  // The dir must exist and rev must be a valid revision.
   167  func (v *VCS) RevSync(dir, rev string) error {
   168  	return v.run(dir, v.vcs.TagSyncCmd, "tag", rev)
   169  }
   170  
   171  // run runs the command line cmd in the given directory.
   172  // keyval is a list of key, value pairs.  run expands
   173  // instances of {key} in cmd into value, but only after
   174  // splitting cmd into individual arguments.
   175  // If an error occurs, run prints the command line and the
   176  // command's combined stdout+stderr to standard error.
   177  // Otherwise run discards the command's output.
   178  func (v *VCS) run(dir string, cmdline string, kv ...string) error {
   179  	_, err := v.run1(dir, cmdline, kv, true)
   180  	return err
   181  }
   182  
   183  // runVerboseOnly is like run but only generates error output to standard error in verbose mode.
   184  func (v *VCS) runVerboseOnly(dir string, cmdline string, kv ...string) error {
   185  	_, err := v.run1(dir, cmdline, kv, false)
   186  	return err
   187  }
   188  
   189  // runOutput is like run but returns the output of the command.
   190  func (v *VCS) runOutput(dir string, cmdline string, kv ...string) ([]byte, error) {
   191  	return v.run1(dir, cmdline, kv, true)
   192  }
   193  
   194  // runOutputVerboseOnly is like runOutput but only generates error output to standard error in verbose mode.
   195  func (v *VCS) runOutputVerboseOnly(dir string, cmdline string, kv ...string) ([]byte, error) {
   196  	return v.run1(dir, cmdline, kv, false)
   197  }
   198  
   199  // run1 is the generalized implementation of run and runOutput.
   200  func (v *VCS) run1(dir string, cmdline string, kv []string, verbose bool) ([]byte, error) {
   201  	m := make(map[string]string)
   202  	for i := 0; i < len(kv); i += 2 {
   203  		m[kv[i]] = kv[i+1]
   204  	}
   205  	args := strings.Fields(cmdline)
   206  	for i, arg := range args {
   207  		args[i] = expand(m, arg)
   208  	}
   209  
   210  	_, err := exec.LookPath(v.vcs.Cmd)
   211  	if err != nil {
   212  		fmt.Fprintf(os.Stderr, "godep: missing %s command.\n", v.vcs.Name)
   213  		return nil, err
   214  	}
   215  
   216  	cmd := exec.Command(v.vcs.Cmd, args...)
   217  	cmd.Dir = dir
   218  	var buf bytes.Buffer
   219  	cmd.Stdout = &buf
   220  	cmd.Stderr = &buf
   221  	err = cmd.Run()
   222  	out := buf.Bytes()
   223  	if err != nil {
   224  		if verbose {
   225  			fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.vcs.Cmd, strings.Join(args, " "))
   226  			os.Stderr.Write(out)
   227  		}
   228  		return nil, err
   229  	}
   230  	return out, nil
   231  }
   232  
   233  func expand(m map[string]string, s string) string {
   234  	for k, v := range m {
   235  		s = strings.Replace(s, "{"+k+"}", v, -1)
   236  	}
   237  	return s
   238  }
   239  
   240  // Mercurial has no command equivalent to git remote add.
   241  // We handle it as a special case in process.
   242  func hgLink(dir, remote, url string) error {
   243  	hgdir := filepath.Join(dir, ".hg")
   244  	if err := os.MkdirAll(hgdir, 0777); err != nil {
   245  		return err
   246  	}
   247  	path := filepath.Join(hgdir, "hgrc")
   248  	f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
   249  	if err != nil {
   250  		return err
   251  	}
   252  	fmt.Fprintf(f, "[paths]\n%s = %s\n", remote, url)
   253  	return f.Close()
   254  }