-
Notifications
You must be signed in to change notification settings - Fork 0
/
go-utility.go
86 lines (68 loc) · 1.82 KB
/
go-utility.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"html/template"
"io"
"log"
"strings"
git "gopkg.in/src-d/go-git.v4"
gitplumming "gopkg.in/src-d/go-git.v4/plumbing"
)
var goModTemplate = template.Must(template.New("package").Parse(`module {{ .PackageName }}
require ({{ range $i, $SharedModule := .SharedModules }}
{{ $SharedModule.URL }} {{ $SharedModule.Hash }}{{ end }}
)
`))
type SharedModule struct {
URL string
Hash string
}
func convertGitModulesToSharedModule(gitSubmodules git.Submodules) ([]SharedModule, error) {
var (
sharedModules = []SharedModule{}
)
for _, gitModule := range gitSubmodules {
var (
err error
gitPath string
gitHash gitplumming.Hash
goURL string
)
if gitPath, gitHash, err = getSubmodulePathAndHash(gitModule); err != nil {
log.Println("unable to get path and status:", err.Error())
continue
}
if goURL, err = gitPathToGoURL(gitPath); err != nil {
log.Println("unable to convert git path to go url", err.Error())
continue
}
sharedModules = append(sharedModules, SharedModule{
URL: goURL,
Hash: fmt.Sprintf("%s", gitHash),
})
}
return sharedModules, nil
}
func gitPathToGoURL(gitPath string) (string, error) {
var (
directoryComponents []string
)
directoryComponents = strings.Split(gitPath, "/")
if len(directoryComponents) < 1 {
return "", fmt.Errorf("path can't be in vendor directory")
}
if directoryComponents[0] != "vendor" {
return "", fmt.Errorf("path isn't in the vendor directory")
}
return strings.Join(directoryComponents[1:], "/"), nil
}
func writeGoModFile(writer io.Writer, packageName string, sharedModules []SharedModule) error {
var goModInfo = struct {
PackageName string
SharedModules []SharedModule
}{
PackageName: packageName,
SharedModules: sharedModules,
}
return goModTemplate.Execute(writer, goModInfo)
}