Skip to content

Commit e7d1f00

Browse files
author
Tsuzu
committed
Add Module
1 parent 4bcdec6 commit e7d1f00

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

module.go

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package gopackages
2+
3+
import (
4+
"path/filepath"
5+
6+
"golang.org/x/xerrors"
7+
)
8+
9+
type Module struct {
10+
module string
11+
rootDir string
12+
}
13+
14+
func NewModule(in string) (*Module, error) {
15+
gmp, err := GetGoModPath(in)
16+
17+
if err != nil {
18+
return nil, xerrors.Errorf("failed to call GetGoModPath: %w", err)
19+
}
20+
21+
module, err := GetGoModule(gmp)
22+
23+
if err != nil {
24+
return nil, xerrors.Errorf("failed to call GetGoModule: %w", err)
25+
}
26+
27+
rootDir, err := filepath.Abs(filepath.Dir(gmp))
28+
29+
if err != nil {
30+
return nil, xerrors.Errorf("failed to get absolute path for the directory of go.mod: %w", err)
31+
}
32+
33+
return &Module{
34+
module: module,
35+
rootDir: rootDir,
36+
}, nil
37+
}
38+
39+
func (m *Module) GetImportPath(path string) (string, error) {
40+
abs, err := filepath.Abs(path)
41+
42+
if err != nil {
43+
return "", xerrors.Errorf("failed to get absolute path for %s: %w", path, err)
44+
}
45+
46+
rel, err := filepath.Rel(m.rootDir, abs)
47+
48+
if err != nil {
49+
return "", xerrors.Errorf("failed to calculate relative path from %s to %s: %w", m.rootDir, abs, err)
50+
}
51+
52+
return filepath.Join(m.module, rel), nil
53+
}

module_test.go

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package gopackages
2+
3+
import "testing"
4+
5+
func TestModule_GetImportPath(t *testing.T) {
6+
m, err := NewModule(".")
7+
8+
if err != nil {
9+
t.Fatal(err)
10+
}
11+
12+
type args struct {
13+
path string
14+
}
15+
tests := []struct {
16+
name string
17+
args args
18+
want string
19+
wantErr bool
20+
}{
21+
{
22+
name: "normal",
23+
args: args{
24+
path: "./tests",
25+
},
26+
want: "github.com/go-utils/gopackages/tests",
27+
wantErr: false,
28+
},
29+
}
30+
for _, tt := range tests {
31+
t.Run(tt.name, func(t *testing.T) {
32+
got, err := m.GetImportPath(tt.args.path)
33+
if (err != nil) != tt.wantErr {
34+
t.Errorf("Module.GetImportPath() error = %v, wantErr %v", err, tt.wantErr)
35+
return
36+
}
37+
if got != tt.want {
38+
t.Errorf("Module.GetImportPath() = %v, want %v", got, tt.want)
39+
}
40+
})
41+
}
42+
}

0 commit comments

Comments
 (0)