Skip to content

Instantly share code, notes, and snippets.

@shouichi
Created November 5, 2016 11:55
Show Gist options
  • Save shouichi/0c08c051a235825a26732b9657829e5a to your computer and use it in GitHub Desktop.
Save shouichi/0c08c051a235825a26732b9657829e5a to your computer and use it in GitHub Desktop.
// Prints dependent packages (including test ones) of the given package.
// $ deps github.com/foo/bar/baz
// net
// net/http
// net/http/httptrace
// net/http/httputil
// net/http/internal
// net/textproto
// net/url
// os
// os/exec
// os/user
// path
// path/filepath
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"sort"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("usage: %s <pkg>\n", os.Args[0])
os.Exit(-1)
}
cmd := exec.Command("go", "list", "-json", os.Args[1])
var stdout bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
os.Exit(1)
}
pkgs := []pkg{}
stack := 0
var buf bytes.Buffer
for {
c, err := stdout.ReadByte()
if err == io.EOF {
break
}
if err != nil {
os.Exit(1)
}
buf.WriteByte(c)
switch c {
case 123: // '{'
stack++
case 125: // '}'
stack--
if stack == 0 {
var pkg pkg
dec := json.NewDecoder(&buf)
if err := dec.Decode(&pkg); err != nil {
fmt.Println(err)
os.Exit(-1)
}
pkgs = append(pkgs, pkg)
}
}
}
deps := []string{}
for _, p := range pkgs {
deps = append(deps, p.ImportPath)
deps = append(deps, p.Deps...)
}
var curr string
sort.Strings(deps)
for _, d := range deps {
if curr != d {
fmt.Println(d)
curr = d
}
}
}
// taken from "go list -h"
type pkg struct {
ImportPath string // import path of package in dir
Deps []string // all (recursively) imported dependencies
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment