Home

gomodinit @main - refs - log - search -
https://git.jolheiser.com/gomodinit.git
go mod init
gomodinit_test.go - raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/matryer/is"
)

func TestModule(t *testing.T) {
	tmp := t.TempDir()

	tt := []struct {
		Name          string
		Path          string
		Expected      string
		GoModInitFile string
	}{
		{
			Name:     "gitea",
			Path:     "gitea.com/user1/repo",
			Expected: "gitea.com/user1/repo",
		},
		{
			Name:     "gitea_sub",
			Path:     "gitea.com/user2/repo/subpkg",
			Expected: "gitea.com/user2/repo/subpkg",
		},
		{
			Name:     "no_uri",
			Path:     "giteacom/user3/repo",
			Expected: "%s/giteacom/user3/repo",
		},
		{
			Name:          ".gomodinit",
			Path:          "gitea.com/user3/repo",
			Expected:      "go.gitea.com/user3/repo",
			GoModInitFile: "go.gitea.com",
		},
	}

	for _, tc := range tt {
		t.Run(tc.Name, func(t *testing.T) {
			assert := is.New(t)

			dir := filepath.Join(tmp, tc.Path)

			err := os.MkdirAll(dir, os.ModePerm)
			assert.NoErr(err) // Should create temp dir

			if tc.GoModInitFile != "" {
				fi, err := os.Create(filepath.Join(tmp, "gitea.com", ".gomodinit"))
				assert.NoErr(err) // Should create .gomodinit file
				_, err = fi.WriteString(tc.GoModInitFile)
				assert.NoErr(err)        // Should write to .gomodinit file
				assert.NoErr(fi.Close()) // Should close .gomodinit file
			}

			err = os.Chdir(dir)
			assert.NoErr(err) // Should chdir to temp dir

			name, err := module()
			assert.NoErr(err) // Should get module name

			expected := tc.Expected
			if strings.Contains(expected, "%s") {
				expected = fmt.Sprintf(expected, tmp)
			}

			assert.Equal(name, expected) // Module name should match expected name
		})
	}
}