From 301a3754aa06870805b37dd0eccee079de90c852 Mon Sep 17 00:00:00 2001 From: Yonghwan SO Date: Sat, 14 May 2022 02:22:10 +0900 Subject: [PATCH] fill importpath when go.mod exists (#11) --- dir.go | 4 ++++ dir_test.go | 65 ++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 59 insertions(+), 10 deletions(-) diff --git a/dir.go b/dir.go index 95be28d..074fac1 100644 --- a/dir.go +++ b/dir.go @@ -80,5 +80,9 @@ func fromNonGoDir(dir string) (Info, error) { return i, fmt.Errorf("here.nonGoDir: %s: %w", dir, err) } + if i.ImportPath == "" && i.Module.Path != "command-line-arguments" { + i.ImportPath = i.Module.Path + } + return i, nil } diff --git a/dir_test.go b/dir_test.go index 2a9b72a..5ccdbd6 100644 --- a/dir_test.go +++ b/dir_test.go @@ -14,26 +14,60 @@ func Test_Dir(t *testing.T) { root, err := os.Getwd() r.NoError(err) - h := New() - - info, err := h.Dir(root) + info, err := Dir(root) r.NoError(err) sanityCheck(t, info) +} + +func Test_Dir_NonGoDir(t *testing.T) { + r := require.New(t) + + root, err := os.Getwd() + r.NoError(err) + + empty := filepath.Join(root, "..", "empty") + os.MkdirAll(empty, 0755) + defer os.RemoveAll(empty) + + info, err := Dir(empty) + r.NoError(err) + r.NotZero(info) + + r.Equal(empty, info.Dir) + r.Equal("", info.Module.GoMod) + r.Equal("", info.ImportPath) + r.Equal("empty", info.Name) + r.Empty(info.GoFiles) + r.Empty(info.Imports) +} + +func Test_Dir_Within(t *testing.T) { + r := require.New(t) + + root, err := os.Getwd() + r.NoError(err) cmd := filepath.Join(root, "cmd") - info, err = h.Dir(cmd) + info, err := Dir(cmd) r.NoError(err) r.NotZero(info) r.Equal(cmd, info.Dir) r.Equal(filepath.Join(root, "go.mod"), info.Module.GoMod) - r.Equal("", info.ImportPath) + r.Equal("github.com/gobuffalo/here", info.ImportPath) r.Equal("cmd", info.Name) r.Empty(info.GoFiles) r.Empty(info.Imports) +} + +func Test_Dir_CmdHere(t *testing.T) { + r := require.New(t) + + root, err := os.Getwd() + r.NoError(err) - cmd = filepath.Join(cmd, "here") - info, err = h.Dir(cmd) + cmd := filepath.Join(root, "cmd", "here") + info, err := Dir(cmd) r.NoError(err) r.NotZero(info) @@ -43,9 +77,16 @@ func Test_Dir(t *testing.T) { r.Equal("main", info.Name) r.NotEmpty(info.GoFiles) r.NotEmpty(info.Imports) +} + +func Test_Dir_File(t *testing.T) { + r := require.New(t) - cmd = filepath.Join(cmd, "main.go") - info, err = h.Dir(cmd) + root, err := os.Getwd() + r.NoError(err) + + cmd := filepath.Join(root, "cmd", "here", "main.go") + info, err := Dir(cmd) r.NoError(err) r.NotZero(info) @@ -55,8 +96,12 @@ func Test_Dir(t *testing.T) { r.Equal("main", info.Name) r.NotEmpty(info.GoFiles) r.NotEmpty(info.Imports) +} + +func Test_Dir_Unknown(t *testing.T) { + r := require.New(t) - info, err = h.Dir("/unknown") + info, err := Dir("/unknown") r.Error(err) r.Zero(info) }