-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (85 loc) · 2.45 KB
/
main.go
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
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/flowdev/go2md/goast"
)
var localLinks bool
func init() {
const (
localLinksDefault = false
localLinksUsage = "create links to local files in markdown"
)
flag.BoolVar(&localLinks, "local", localLinksDefault, localLinksUsage)
flag.BoolVar(&localLinks, "l", localLinksDefault, localLinksUsage+" (shorthand)")
}
func main() {
flag.Parse()
srcRoots := findSourceRoots()
projRoot := getOutputOfCmd("git", "rev-parse", "--show-toplevel")
fmt.Println("srcRoots:", srcRoots)
fmt.Println("localLinks:", localLinks)
fmt.Println("projRoot:", projRoot)
if err := goast.ProcessDir(".", goast.NewPackageDict(srcRoots, projRoot, localLinks)); err != nil {
log.Printf("FATAL: Unable to process current directory: %v", err)
}
}
// findSourceRoots finds all the possible roots for Go source code in the right
// order.
func findSourceRoots() []string {
srcRoots := make([]string, 0, 4)
vendorRoot := findVendorRoot()
if vendorRoot != "" {
srcRoots = append(srcRoots, vendorRoot)
}
srcRoots = append(srcRoots, findGoPathRoots()...)
goRootRoot := findGoRootRoot()
if goRootRoot != "" {
srcRoots = append(srcRoots, goRootRoot)
}
return srcRoots
}
// findGoPathRoots finds all paths of GOPATH and turns them into source roots.
func findGoPathRoots() []string {
gopath := getOutputOfCmd("go", "env", "GOPATH")
gopaths := filepath.SplitList(gopath)
srcRoots := make([]string, len(gopaths))
for i, gp := range gopaths {
srcRoots[i] = filepath.Join(gp, "src")
}
return srcRoots
}
func findVendorRoot() string {
return crawlUpDirsAndFind("vendor", ".")
}
func findGoRootRoot() string {
return filepath.Join(getOutputOfCmd("go", "env", "GOROOT"), "src")
}
func getOutputOfCmd(cmd string, args ...string) string {
out, err := exec.Command(cmd, args...).Output()
if err != nil {
log.Fatalf("FATAL: Unable to execute command: %v", err)
}
return strings.TrimRight(string(out), "\r\n")
}
func crawlUpDirsAndFind(file, startDir string) string {
absDir, err := filepath.Abs(startDir)
if err != nil {
log.Fatalf("FATAL: Unable to find absolute directory (for %s): %v", startDir, err)
}
volName := filepath.VolumeName(absDir)
oldDir := "" // set to impossible value first!
for ; absDir != volName && absDir != oldDir; absDir = filepath.Dir(absDir) {
path := filepath.Join(absDir, file)
if _, err = os.Stat(path); err == nil {
return path
}
oldDir = absDir
}
return ""
}