diff --git a/foreach.go b/foreach.go new file mode 100644 index 0000000..5055c0f --- /dev/null +++ b/foreach.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "io" + "log" + "os" + "os/exec" +) + +var cmdForeach = &Command{ + Name: "foreach", + Short: "run a command in each dependency's path", + Long: ` +Foreach runs the provided command for each dependency path in GOPATH. This can +be useful for checking out the master branch after running "godep restore" to +avoid breaking "go get -u". + +`, + Run: runForeach, + OnlyInGOPATH: true, +} + +func runForeach(cmd *Command, args []string) { + g, err := loadDefaultGodepsFile() + if err != nil { + log.Fatalln(err) + } + + if args == nil || len(args) < 1 { + log.Fatalln("Must provide a command to foreach") + } + + for _, dep := range g.Deps { + c := exec.Command(args[0], args[1:]...) + c.Dir = getRoot(dep.root, dep.ImportPath) + + fmt.Fprintf(os.Stderr, "\n%s:\n", dep.ImportPath) + out, err := c.StdoutPipe() + if err != nil { + log.Fatalln(err) + } + + serr, err := c.StderrPipe() + if err != nil { + log.Fatalln(err) + } + + go io.Copy(os.Stdout, out) + go io.Copy(os.Stderr, serr) + + err = c.Run() + if err != nil { + log.Fatalln(err) + } + } +} diff --git a/main.go b/main.go index b1abebe..e2c7314 100644 --- a/main.go +++ b/main.go @@ -65,6 +65,7 @@ var commands = []*Command{ cmdGet, cmdPath, cmdRestore, + cmdForeach, cmdUpdate, cmdDiff, cmdVersion, diff --git a/restore.go b/restore.go index 9de53e0..c416814 100644 --- a/restore.go +++ b/restore.go @@ -25,6 +25,13 @@ https://github.com/golang/go/commit/42206598671a44111c8f726ad33dc7b265bdf669. OnlyInGOPATH: true, } +func getRoot(root, path string) string { + if root == "" { + return filepath.Join(filepath.SplitList(build.Default.GOPATH)[0], "src", path) + } + return root +} + // Three phases: // 1. Download all deps // 2. Restore all deps (checkout the recorded rev) @@ -104,15 +111,12 @@ func download(dep *Dependency) error { continue } if fi.IsDir() { - dep.root = t + // If none found, just pick the first GOPATH entry (AFAICT that's what go get does) + dep.root = getRoot(t, rr.Root) break } } - // If none found, just pick the first GOPATH entry (AFAICT that's what go get does) - if dep.root == "" { - dep.root = filepath.Join(filepath.SplitList(build.Default.GOPATH)[0], "src", rr.Root) - } ppln("dep", dep) if downloaded[rr.Repo] {