-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodule.go
53 lines (38 loc) · 1.04 KB
/
module.go
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
package gopackages
import (
"path/filepath"
"golang.org/x/xerrors"
)
type Module struct {
module string
rootDir string
}
func NewModule(in string) (*Module, error) {
gmp, err := GetGoModPath(in)
if err != nil {
return nil, xerrors.Errorf("failed to call GetGoModPath: %w", err)
}
module, err := GetGoModule(gmp)
if err != nil {
return nil, xerrors.Errorf("failed to call GetGoModule: %w", err)
}
rootDir, err := filepath.Abs(filepath.Dir(gmp))
if err != nil {
return nil, xerrors.Errorf("failed to get absolute path for the directory of go.mod: %w", err)
}
return &Module{
module: module,
rootDir: rootDir,
}, nil
}
func (m *Module) GetImportPath(path string) (string, error) {
abs, err := filepath.Abs(path)
if err != nil {
return "", xerrors.Errorf("failed to get absolute path for %s: %w", path, err)
}
rel, err := filepath.Rel(m.rootDir, abs)
if err != nil {
return "", xerrors.Errorf("failed to calculate relative path from %s to %s: %w", m.rootDir, abs, err)
}
return filepath.Join(m.module, rel), nil
}