check if there a go.mod in a directory without any go files

This commit is contained in:
aperezg 2019-11-09 20:43:22 +01:00
parent 6cf141c51a
commit 71d20943f0
2 changed files with 41 additions and 9 deletions

View File

@ -2,6 +2,7 @@ package here
import ( import (
"encoding/json" "encoding/json"
"fmt"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -39,20 +40,30 @@ func Dir(p string) (Info, error) {
return i, err return i, err
} }
if strings.Contains(es, "can't load package: package .") {
if _, err := os.Stat(fmt.Sprintf("%s/go.mod", p)); err == nil {
var mod Module
bm, err := run ("go", "list", "-m", "-json")
if err != nil {
return i, err
}
if err := json.Unmarshal(bm, &mod); err != nil {
return i, err
}
info := NewInfoFromPath(p, mod)
prepareInfo(p, info, &i)
return i, err
}
}
info, err := Dir(filepath.Dir(p)) info, err := Dir(filepath.Dir(p))
if err != nil { if err != nil {
return info, err return info, err
} }
i.Module = info.Module
ph := strings.TrimPrefix(p, info.Module.Dir)
i.ImportPath = path.Join(info.Module.Path, ph)
i.Name = path.Base(i.ImportPath)
ph = filepath.Join(info.Module.Dir, ph)
i.Dir = ph
prepareInfo(p, info, &i)
return i, err return i, err
} }
@ -73,3 +84,14 @@ func Dir(p string) (Info, error) {
return i, nil return i, nil
} }
func prepareInfo(p string, info Info, target *Info) {
target.Module = info.Module
ph := strings.TrimPrefix(p, target.Module.Dir)
target.ImportPath = path.Join(info.Module.Path, ph)
target.Name = path.Base(target.ImportPath)
ph = filepath.Join(info.Module.Dir, ph)
target.Dir = ph
}

View File

@ -16,6 +16,16 @@ type Info struct {
Module Module Module Module
} }
// NewInfoFromPath initialize a Info with a basic information and his module
// this method could be used when the Unmarshal information is not possible
func NewInfoFromPath(path string, m Module) Info {
return Info{
Dir: path,
ImportPath: "command-line-arguments",
Module: m,
}
}
func (fi Info) MarshalJSON() ([]byte, error) { func (fi Info) MarshalJSON() ([]byte, error) {
mm := map[string]interface{}{ mm := map[string]interface{}{
"ImportPath": fi.ImportPath, "ImportPath": fi.ImportPath,