Repository navigation
Expand file tree
/
Copy pathguess_deps.go
More file actions
95 lines (85 loc) · 1.97 KB
/
Copy pathguess_deps.go
File metadata and controls
95 lines (85 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package cmd
import (
"bytes"
"github.com/Masterminds/cookoo"
"go/build"
"os"
"strings"
"text/template"
"fmt"
)
var yamlGuessTpl = `
# Detected project's dependencies.
import:{{range $path, $notLocal := .}}
- package: {{$path}}{{end}}
`
// GuessDeps tries to get the dependencies for the current directory.
//
// Params
// - dirname (string): Directory to use as the base. Default: "."
func GuessDeps(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
base := p.Get("dirname", ".").(string)
deps := make(map[string]bool)
err := findDeps(deps, base)
deps = compactDeps(deps)
delete(deps, base)
if err != nil {
return nil, err
}
tmpl, err := template.New("main").Parse(yamlGuessTpl)
if err != nil {
return nil, err
}
var doc bytes.Buffer
tmpl.Execute(&doc, deps)
fmt.Println(doc.String())
return doc, nil
}
// https://golang.org/src/cmd/go/pkg.go#485
func findDeps(soFar map[string]bool, name string) error {
cwd, err := os.Getwd()
if err != nil {
return err
}
pkg, err := build.Import(name, cwd, 0)
if err != nil {
return err
}
if pkg.Goroot {
return nil
}
soFar[pkg.ImportPath] = true
for _, imp := range pkg.Imports {
if !soFar[imp] {
if err := findDeps(soFar, imp); err != nil {
return err
}
}
}
return nil
}
// Minimize the package imports. For example, importing github.com/Masterminds/cookoo
// and github.com/Masterminds/cookoo/io should not import two packages. Only one
// package needs to be referenced.
func compactDeps(soFar map[string]bool) map[string]bool {
/*
for k, _ := range soFar {
for subkey, _ := range soFar {
if strings.HasPrefix(subkey, k) && subkey != k {
delete(soFar, subkey)
}
}
}
*/
// MPB: Making this a little more aggressive.
basePackages := make(map[string]bool, len(soFar))
for k, _ := range soFar {
parts := strings.SplitN(k, "/", 4)
if len(parts) < 4 {
basePackages[k] = true
} else {
basePackages[strings.Join(parts[0:3], "/")] = true
}
}
return basePackages
}