Skip to content
This repository has been archived by the owner on Feb 26, 2019. It is now read-only.

Add foreach command to run a shell command in each dependency's directory #499

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions foreach.go
Original file line number Diff line number Diff line change
@@ -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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be run for each dep or each repo?


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)
}
}
}
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ var commands = []*Command{
cmdGet,
cmdPath,
cmdRestore,
cmdForeach,
cmdUpdate,
cmdDiff,
cmdVersion,
Expand Down
14 changes: 9 additions & 5 deletions restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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] {
Expand Down