Skip to content

Commit

Permalink
fix: PkgSourceDir 现在支持返回子路径
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed May 10, 2024
1 parent 8b3dbdc commit c21aa9d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
4 changes: 2 additions & 2 deletions mod.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var (
// replace 是否考虑 go.mod 中的 replace 指令的影响;
//
// NOTE: 这并不会检测 dir 指向目录是否真实且准确。
func ModSourceDir(pkgPath, modDir string, replace bool) (dir string, err error) {
func PkgSourceDir(pkgPath, modDir string, replace bool) (dir string, err error) {
if strings.IndexByte(pkgPath, '.') < 0 {
return filepath.Join(stdSource, pkgPath), nil
}
Expand Down Expand Up @@ -135,7 +135,7 @@ LOOP:
}
}

// PkgPath 文件或目录 p 所在 Go 文件的导出路径
// PkgPath 文件或目录 p 的导出路径
//
// 会向上查找 go.mod,根据 go.mod 中的 module 结合当前目录组成当前目录的导出路径。
func PkgPath(p string) (string, error) {
Expand Down
16 changes: 8 additions & 8 deletions mod_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,37 @@ import (
"github.com/issue9/assert/v4"
)

func TestModSourceDir(t *testing.T) {
func TestPkgSourceDir(t *testing.T) {
a := assert.New(t, false)

// std
dir, err := ModSourceDir("encoding/json", "./", false)
dir, err := PkgSourceDir("encoding/json", "./", false)
a.NotError(err).FileExists(dir)

dir, err = ModSourceDir("note-exists", "./", false)
dir, err = PkgSourceDir("note-exists", "./", false)
a.NotError(err).FileNotExists(dir)

// require

dir, err = ModSourceDir("github.com/issue9/assert/v4", "./", false)
dir, err = PkgSourceDir("github.com/issue9/assert/v4", "./", false)
a.NotError(err).FileExists(dir).
True(strings.HasSuffix(filepath.ToSlash(dir), "assert/[email protected]"))

dir, err = ModSourceDir("github.com/issue9/assert/v4/rest", "./", false)
dir, err = PkgSourceDir("github.com/issue9/assert/v4/rest", "./", false)
a.NotError(err).FileExists(dir).
True(strings.HasSuffix(filepath.ToSlash(dir), "assert/[email protected]/rest"))

// replace

dir, err = ModSourceDir("github.com/issue9/web/v2", "./testdata/go.mod", true)
dir, err = PkgSourceDir("github.com/issue9/web/v2", "./testdata/go.mod", true)
a.NotError(err).NotEmpty(dir) // 此处 dir 可能不存在,因为 go.mod 关于 web 的包是随便指定的

dir, err = ModSourceDir("github.com/issue9/source", "./testdata/go.mod", true)
dir, err = PkgSourceDir("github.com/issue9/source", "./testdata/go.mod", true)
a.NotError(err).FileExists(dir)

// not exist

dir, err = ModSourceDir("github.com/issue9/not-exists", "./testdata/go.mod", true)
dir, err = PkgSourceDir("github.com/issue9/not-exists", "./testdata/go.mod", true)
a.ErrorIs(err, fs.ErrNotExist).Empty(dir)
}

Expand Down

0 comments on commit c21aa9d

Please sign in to comment.