-
Notifications
You must be signed in to change notification settings - Fork 1
/
magefile.go
287 lines (255 loc) · 6.49 KB
/
magefile.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//go:build mage
// +build mage
package main
import (
"bytes"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"text/template"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/spachava753/kpkg/pkg/util"
"github.com/magefile/mage/mg" // mg contains helpful utility functions, like Deps
)
// Default target to run when none is specified
// If not set, running mage will list available targets
// var Default = Build
// A build step that requires additional params, or platform specific steps for example
func Build() error {
mg.Deps(InstallDeps)
fmt.Println("Building...")
cmd := exec.Command("go", "build", "-o", "kpkg", ".")
return cmd.Run()
}
// A install step
func Install() error {
mg.Deps(InstallDeps)
fmt.Println("Installing...")
goVer := runtime.Version()
ver := "0.3.0"
r, err := git.PlainOpen(".")
if err != nil {
return fmt.Errorf("could not instantiate git repo: %w", err)
}
revision := "main"
h, err := r.ResolveRevision(plumbing.Revision(revision))
if err != nil {
return fmt.Errorf("could not resolve git revision: %w", err)
}
fmt.Println("revision", h.String())
ldflags := fmt.Sprintf(
"-X 'main.version=%s' -X 'main.commit=%s' -X 'main.goVersion=%s' -X 'main.cliOs=%s' -X 'main.cliArch=%s'",
ver,
h.String(),
goVer,
runtime.GOOS,
runtime.GOARCH,
)
fmt.Printf("ldflags: %s\n", ldflags)
cmd := exec.Command("go", "install", "-ldflags="+ldflags)
fmt.Println(cmd.String())
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
err = cmd.Run()
if err != nil {
return fmt.Errorf("could not run command, err: %s", err)
}
return nil
}
// Manage your deps, or running package managers.
func InstallDeps() error {
fmt.Println("Installing Deps...")
cmd := exec.Command("go", "list", "./...")
if err := cmd.Run(); err != nil {
return err
}
cmd = exec.Command("go", "mod", "tidy")
return cmd.Run()
}
// A step to clean up after yourself
func Clean() error {
fmt.Println("Cleaning...")
cmd := exec.Command("rm", "-rf", "./kpkg")
return cmd.Run()
}
// A step to generate code for a new Github release tool;
// accepts the tool name (camelCase), the Github org, and the repo name
func GenGithubTool(toolName, org, repoName string) error {
templateCode := `package {{ .pkgName }}
import (
"fmt"
"github.com/Masterminds/semver"
kpkgerr "github.com/spachava753/kpkg/pkg/error"
"github.com/spachava753/kpkg/pkg/tool"
)
type {{ .structName }} struct {
arch,
os string
tool.GithubReleaseTool
}
func (l {{ .structName }}) Name() string {
return "{{ .toolName }}"
}
func (l {{ .structName }}) ShortDesc() string {
return "REPLACE ME"
}
func (l {{ .structName }}) LongDesc() string {
return "REPLACE ME"
}
func (l {{ .structName }}) MakeUrl(version string) (string, error) {
v, err := semver.NewVersion(version)
if err != nil {
return "", err
}
version = v.String()
url := fmt.Sprintf("%s%s/{{ .repoName }}", l.MakeReleaseUrl(), version)
switch {
case l.os == "darwin" && l.arch == "amd64":
url += l.os + "_" + l.arch
case l.os == "windows" && l.arch == "amd64":
url += l.os + "_" + l.arch + ".exe"
case l.os == "linux" && l.arch == "amd64",
l.os == "linux" && l.arch == "arm64":
url += l.os + "_" + l.arch
default:
return "", &kpkgerr.UnsupportedRuntimeErr{Binary: l.Name()}
}
return url, nil
}
func MakeBinary(os, arch string) tool.Binary {
return {{ .structName }}{
arch: arch,
os: os,
GithubReleaseTool: tool.MakeGithubReleaseTool("{{ .org }}", "{{ .repoName }}"),
}
}
`
// package names should be lowercase
pkgName := strings.ToLower(toolName)
// and shouldn't contain hyphens. This will also be the folder name
pkgName = strings.ReplaceAll(pkgName, "-", "")
fmt.Printf("pkg name will be %s\n", pkgName)
// make sure that the folder doesn't exist
folderPath := filepath.Join("pkg", "tool", pkgName)
var folderExists bool
info, err := os.Stat(folderPath)
if err == nil {
if !info.IsDir() {
fmt.Errorf(
"found a file with the conflicting name %s, delete this file first",
pkgName,
)
}
// since the dir already exists, make sure to check that we can create the file
var files []string
filepath.Walk(
folderPath, func(path string, info fs.FileInfo, err error) error {
if info.IsDir() {
return nil
}
files = append(files, path)
return nil
},
)
if files != nil && util.ContainsString(files, pkgName) {
fmt.Errorf(
"filepath %s already exists", filepath.Join(folderPath, pkgName),
)
}
folderExists = true
}
structName := ToLowerCamel(toolName) + "Tool"
tmpl, err := template.New("template code").Parse(templateCode)
if err != nil {
return err
}
var bytes bytes.Buffer
err = tmpl.Execute(
&bytes, map[string]string{
"pkgName": pkgName,
"structName": structName,
"toolName": toolName,
"org": org,
"repoName": repoName,
},
)
if err != nil {
return err
}
// create a new folder if it doesn't exist
if !folderExists {
fmt.Printf("creating folder %s\n", folderPath)
if err := os.Mkdir(folderPath, 0775); err != nil {
return err
}
} else {
fmt.Printf("folder exists %s, skipping creation\n", folderPath)
}
// create the file
codePath := filepath.Join(folderPath, pkgName+".go")
fmt.Printf("creating file at location %s\n", codePath)
f, err := os.Create(codePath)
if err != nil {
return err
}
// and dump the code
fmt.Printf("dumping template code in %s\n", codePath)
_, err = io.Copy(f, &bytes)
return err
}
// COPIED BELOW CODE FROM https://github.com/iancoleman/strcase
var uppercaseAcronym = map[string]string{
"ID": "id",
}
// Converts a string to CamelCase
func toCamelInitCase(s string, initCase bool) string {
s = strings.TrimSpace(s)
if s == "" {
return s
}
if a, ok := uppercaseAcronym[s]; ok {
s = a
}
n := strings.Builder{}
n.Grow(len(s))
capNext := initCase
for i, v := range []byte(s) {
vIsCap := v >= 'A' && v <= 'Z'
vIsLow := v >= 'a' && v <= 'z'
if capNext {
if vIsLow {
v += 'A'
v -= 'a'
}
} else if i == 0 {
if vIsCap {
v += 'a'
v -= 'A'
}
}
if vIsCap || vIsLow {
n.WriteByte(v)
capNext = false
} else if vIsNum := v >= '0' && v <= '9'; vIsNum {
n.WriteByte(v)
capNext = true
} else {
capNext = v == '_' || v == ' ' || v == '-' || v == '.'
}
}
return n.String()
}
// ToCamel converts a string to CamelCase
func ToCamel(s string) string {
return toCamelInitCase(s, true)
}
// ToLowerCamel converts a string to lowerCamelCase
func ToLowerCamel(s string) string {
return toCamelInitCase(s, false)
}