Permalink
Browse files

go-importers

  • Loading branch information...
peter-edge committed Oct 9, 2015
1 parent 2a6ec64 commit fd21420165a257e77b2a9a6f390e50bf79dee5a6
Showing with 76 additions and 0 deletions.
  1. +76 −0 go-importers/main.go
@@ -0,0 +1,76 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"

"go.pedge.io/pkg/exec"
"go.pedge.io/tools/common"
)

func main() {
if err := do(); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
os.Exit(0)
}

func do() error {
pkgs, err := getPackages()
if err != nil {
return err
}
m := make(map[string][]string)
for _, pkg := range pkgs {
importers, err := getImporters(pkg)
if err != nil {
return err
}
if len(importers) > 0 {
m[pkg] = importers
}
}
data, err := json.MarshalIndent(&m, "", "\t")
if err != nil {
return err
}
fmt.Println(string(data))
return nil
}

func getPackages() (_ []string, retErr error) {
buffer := bytes.NewBuffer(nil)
if err := pkgexec.RunStdout(buffer, "go", "list", "./..."); err != nil {
return nil, err
}
return common.GetUniqueSortedLines(buffer)
}

func getImporters(pkg string) (_ []string, retErr error) {
response, err := http.Get(fmt.Sprintf("http://api.godoc.org/importers/%s", pkg))
if err != nil {
return nil, err
}
defer func() {
if err := response.Body.Close(); err != nil && retErr == nil {
retErr = err
}
}()
var result struct {
Results []struct {
Path string
}
}
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return nil, err
}
paths := make([]string, len(result.Results))
for i, r := range result.Results {
paths[i] = r.Path
}
return paths, nil
}

0 comments on commit fd21420

Please sign in to comment.