pkger/here/dir.go

78 lines
1.2 KiB
Go
Raw Permalink Normal View History

2019-08-05 00:13:27 +03:00
package here
import (
"encoding/json"
2019-11-11 02:38:44 +03:00
"fmt"
2019-08-05 00:13:27 +03:00
"os"
"path/filepath"
)
// Dir attempts to gather info for the requested directory.
func Dir(p string) (Info, error) {
2019-09-21 19:51:29 +03:00
i, err := Cache(p, func(p string) (Info, error) {
2019-09-12 04:29:39 +03:00
var i Info
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
fi, err := os.Stat(p)
if err != nil {
return i, err
}
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
if !fi.IsDir() {
p = filepath.Dir(p)
}
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
pwd, err := os.Getwd()
if err != nil {
return i, err
}
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
defer os.Chdir(pwd)
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
os.Chdir(p)
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
b, err := run("go", "list", "-json")
// go: cannot find main module; see 'go help modules'
// build .: cannot find module for path .
// no Go files in
2019-09-12 04:29:39 +03:00
if err != nil {
2019-11-11 02:38:44 +03:00
if nonGoDirRx.MatchString(err.Error()) {
return fromNonGoDir(p)
}
return i, fmt.Errorf("%w %s", err, p)
2019-09-12 04:29:39 +03:00
}
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
if err := json.Unmarshal(b, &i); err != nil {
return i, err
}
2019-08-05 00:13:27 +03:00
2019-09-12 04:29:39 +03:00
return i, nil
})
2019-09-21 19:51:29 +03:00
if err != nil {
return i, err
}
return Cache(i.ImportPath, func(p string) (Info, error) {
2019-09-21 19:51:29 +03:00
return i, nil
})
}
func fromNonGoDir(dir string) (Info, error) {
i := Info{
2019-11-11 02:27:57 +03:00
Dir: dir,
Name: filepath.Base(dir),
}
b, err := run("go", "list", "-json", "-m")
if err != nil {
return i, err
}
if err := json.Unmarshal(b, &i.Module); err != nil {
return i, err
}
return i, err
2019-11-11 01:22:01 +03:00
}