Skip to content

Commit

Permalink
refactor!: ModFile 现在也返回 go.mod 的文件路径
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Nov 21, 2023
1 parent 7b6fa72 commit d6657c9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
16 changes: 11 additions & 5 deletions mod.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,24 @@ const modFile = "go.mod"

// ModFile 查找 p 所在模块的 go.mod 内容
//
// 从当前目录开始依次向上查找 go.mod,从其中获取 module 变量的值
func ModFile(p string) (*modfile.File, error) {
// 从当前目录开始依次向上查找 go.mod,从其中获取 go.mod 文件位置,以及文件内容的解析
func ModFile(p string) (string, *modfile.File, error) {
path, err := modDir(p)
if err != nil {
return nil, err
return "", nil, err
}

data, err := os.ReadFile(path)
if err != nil {
return nil, err
return "", nil, err
}
return modfile.Parse(path, data, nil)

mod, err := modfile.Parse(path, data, nil)
if err != nil {
return "", nil, err
}

return path, mod, nil
}

// ModDir 向上查找 go.mod 所在的目录
Expand Down
12 changes: 6 additions & 6 deletions mod_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,19 @@ import (
func TestModFile(t *testing.T) {
a := assert.New(t, false)

f, err := ModFile("./")
a.NotError(err).NotNil(f).Equal(f.Module.Mod.Path, "github.com/issue9/source")
p, f, err := ModFile("./")
a.NotError(err).NotNil(f).Equal(f.Module.Mod.Path, "github.com/issue9/source").NotEmpty(p)

f, err = ModFile("./testdata")
a.NotError(err).NotNil(f).Equal(f.Module.Mod.Path, "github.com/issue9/source")
p, f, err = ModFile("./testdata")
a.NotError(err).NotNil(f).Equal(f.Module.Mod.Path, "github.com/issue9/source").NotEmpty(p)

// NOTE: 可能不存在 c:\windows\system32 或是 c:\windows\system32 下正好存在一个 go.mod
dir := "/windows/system32"
if runtime.GOOS == "windows" {
dir = "c:\\windows\\system32"
}
f, err = ModFile(dir)
a.Error(err).Nil(f)
p, f, err = ModFile(dir)
a.Error(err).Nil(f).Empty(p)
}

func TestModDir(t *testing.T) {
Expand Down

0 comments on commit d6657c9

Please sign in to comment.