-
Notifications
You must be signed in to change notification settings - Fork 0
/
mainextra.go
50 lines (47 loc) · 1.31 KB
/
mainextra.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
package main
import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"aslevy.com/go-doc/internal/dlog"
"aslevy.com/go-doc/internal/godoc"
"aslevy.com/go-doc/internal/index"
)
func packageIndex() *index.Index {
localModuleRoot := moduleRootDir(goCmd())
if localModuleRoot == "" {
return nil
}
path := indexCachePath(localModuleRoot)
if err := os.Mkdir(filepath.Dir(path), 0755); err != nil && !os.IsExist(err) {
dlog.Printf("failed to create index cache dir: %v", err)
return nil
}
pkgIdx, err := index.Load(context.Background(), path, dirsToIndexModules(codeRoots()...), index.WithMode(index.Sync))
if err != nil {
dlog.Printf("index.Load: %v", err)
}
return pkgIdx
}
func indexCachePath(localModuleRoot string) string {
return filepath.Join(localModuleRoot, ".go-doc", "packages.sqlite3")
}
func dirsToIndexModules(dirs ...Dir) []godoc.PackageDir {
mods := make([]godoc.PackageDir, len(dirs))
for i, dir := range dirs {
mods[i] = godoc.NewPackageDir(dir.importPath, dir.dir)
}
return mods
}
func moduleRootDir(goCmd string) string {
args := []string{"env", "GOMOD"}
stdout, err := exec.Command(goCmd, args...).Output()
if err != nil {
dlog.Printf("failed to run `%s %s`: %v", goCmd, strings.Join(args, " "), err)
return ""
}
return filepath.Dir(string(bytes.TrimSpace(stdout)))
}