Skip to content

Commit

Permalink
create go.mod file even if outside of a Go modules project
Browse files Browse the repository at this point in the history
  • Loading branch information
itchyny committed Dec 31, 2019
1 parent 54bd45e commit aaafbc2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
7 changes: 3 additions & 4 deletions gomod.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
)

func (s *Session) initGoMod() error {
hasMod, replaces, err := getModReplaces()
if err != nil || !hasMod {
replaces, err := getModReplaces()
if err != nil {
return err
}

Expand All @@ -25,7 +25,7 @@ func (s *Session) initGoMod() error {
return ioutil.WriteFile(goModPath, []byte(mod), 0644)
}

func getModReplaces() (hasMod bool, replaces []string, err error) {
func getModReplaces() (replaces []string, err error) {
pwd, err := os.Getwd()
if err != nil {
return
Expand All @@ -45,7 +45,6 @@ func getModReplaces() (hasMod bool, replaces []string, err error) {
return
}

hasMod = true
replaces = append(replaces, "replace "+module+" => "+strconv.Quote(root))

for s.Scan() {
Expand Down
29 changes: 28 additions & 1 deletion session_gomod_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ func chdir(dir string) func() {
return func() { os.Chdir(d) }
}

func setenv(name, value string) func() {
v := os.Getenv(name)
os.Setenv(name, value)
return func() { os.Setenv(name, v) }
}

func gomodSetup(t *testing.T) func() {
tempDir, err := ioutil.TempDir("", "gore-")
require.NoError(t, err)
Expand Down Expand Up @@ -133,8 +139,29 @@ func TestSessionEval_Gomod_DeepDir(t *testing.T) {
assert.Equal(t, ``, stderr.String())
}

func TestSessionEval_Gomod_Outside(t *testing.T) {
stdout, stderr := new(bytes.Buffer), new(bytes.Buffer)
tempDir, _ := ioutil.TempDir("", "gore-")
defer chdir(tempDir)()
s, err := NewSession(stdout, stderr)
defer s.Clear()
require.NoError(t, err)
defer setenv("GOPATH", tempDir)()

codes := []string{
`:i github.com/motemen/gore`,
`gore.NewSession(nil, nil)`,
}

for _, code := range codes {
_ = s.Eval(code)
}

assert.Equal(t, ``, stderr.String())
}

func TestGetCurrentModule(t *testing.T) {
_, replaces, _ := getModReplaces()
replaces, _ := getModReplaces()
pwd, _ := os.Getwd()
expected := "replace github.com/motemen/gore => " + strconv.Quote(pwd)
assert.Equal(t, expected, replaces[0])
Expand Down

0 comments on commit aaafbc2

Please sign in to comment.