-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
424 lines (396 loc) · 10.7 KB
/
main.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package main
import (
"bytes"
"cmp"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/diegosz/flaggy"
"github.com/diegosz/go-archetype/generator"
"github.com/diegosz/go-archetype/log"
"github.com/gogs/git-module"
"github.com/joho/godotenv"
"go.uber.org/multierr"
"golang.org/x/mod/modfile"
"github.com/diegosz/garchetype/internal/gitstat"
)
const (
exeName = "garchetype"
envPrefix = "GARCHETYPE"
transformationPrefix = "transformations-"
transformationExt = "yaml"
defaultArchetypesFolder = "archetypes"
defaultTransformation = "default"
defaultArchetype = "hello-world"
featureNameID = "feature_name"
goModNameID = "gomod_name"
)
var ErrSilentExit = errors.New("silent exit")
func main() {
if err := run(context.Background(), os.Stdout, os.Stderr, os.Args); err != nil {
if !errors.Is(err, ErrSilentExit) {
fmt.Fprintf(os.Stderr, "💥 %s error: %s\n", exeName, err)
}
os.Exit(1)
}
os.Exit(0)
}
type Config struct {
Force bool
FeatureName string
ArchetypesFolder string
Archetype string
Transformation string
SourceDir string
SourceRepo string
}
// newDefaultConfig returns a new default config with the default values set.
func newDefaultConfig() *Config {
var force bool
switch strings.ToLower(os.Getenv(envPrefix + "_VERBOSE")) {
case "yes", "ok", "t", "true":
force = true
default:
}
return &Config{
Force: force,
ArchetypesFolder: cmp.Or(os.Getenv(envPrefix+"_ARCHETYPES_FOLDER"), defaultArchetypesFolder),
Archetype: cmp.Or(os.Getenv(envPrefix+"_ARCHETYPE"), defaultArchetype),
Transformation: cmp.Or(os.Getenv(envPrefix+"_TRANSFORMATION"), defaultTransformation),
SourceDir: os.Getenv(envPrefix + "_SOURCE_DIR"),
SourceRepo: os.Getenv(envPrefix + "_SOURCE_REPO"),
}
}
var environment = []string{
envPrefix + "_ARCHETYPE",
envPrefix + "_ARCHETYPES_FOLDER",
envPrefix + "_ENV",
envPrefix + "_SOURCE_DIR",
envPrefix + "_SOURCE_REPO",
envPrefix + "_TRANSFORMATION",
envPrefix + "_FORCE",
}
func run(_ context.Context, stdout, _ io.Writer, args []string) (err error) {
// Try to read the default .env file in the current path into ENV for this
// process. It WILL NOT OVERRIDE an env variable that already exists -
// consider the .env file to set dev vars or sensible defaults.
_ = godotenv.Load()
flaggy.ShowHelpOnUnexpectedEnable()
flaggy.SetName(exeName)
flaggy.SetDescription("Tool for scaffolding using archetypes.")
flaggy.SetVersion(Version)
if env := os.Getenv(envPrefix + "_ENV"); env != "" {
if err := godotenv.Load(env); err != nil {
return err
}
}
cfg := newDefaultConfig() // Set the default values prior to parsing.
addCommand := flaggy.NewSubcommand("add")
addCommand.Description = "Add a feature using an archetype."
addCommand.Bool(&cfg.Force, "", "force", "Force adding on a dirty repo.")
addCommand.String(&cfg.FeatureName, "f", "feature", "Feature name to add.")
addCommand.String(&cfg.Archetype, "a", "archetype", "Archetype to use.")
addCommand.String(&cfg.Transformation, "t", "transformation", "Transformation to use.")
addCommand.String(&cfg.SourceDir, "s", "source-dir", "Source directory to use.")
addCommand.String(&cfg.SourceRepo, "r", "source-repo", "Source repository to use.")
listCommand := flaggy.NewSubcommand("list")
listCommand.Description = "List available archetypes."
listCommand.String(&cfg.SourceDir, "s", "source-dir", "Source directory to use.")
environmentCommand := flaggy.NewSubcommand("environment")
environmentCommand.Hidden = true
flaggy.AttachSubcommand(addCommand, 1)
flaggy.AttachSubcommand(listCommand, 1)
flaggy.AttachSubcommand(environmentCommand, 1)
flaggy.ParseArgs(args[1:])
switch {
case addCommand.Used:
if _, err := os.Stat("go.mod"); os.IsNotExist(err) {
return errors.New("go.mod file not found in the current folder")
}
if err := setSource(stdout, cfg); err != nil {
return err
}
if cfg.Archetype == "" {
err = multierr.Append(err, errors.New("archetype is required"))
}
if cfg.FeatureName == "" {
cfg.FeatureName = cfg.Archetype
}
if cfg.SourceDir == "" {
err = multierr.Append(err, errors.New("source directory is required"))
}
if err != nil {
return err
}
return addFeature(stdout, cfg, flaggy.TrailingArguments...)
case listCommand.Used:
if err := setSource(stdout, cfg); err != nil {
return err
}
if cfg.SourceDir == "" {
err = multierr.Append(err, errors.New("source directory is required"))
}
if err != nil {
return err
}
return list(stdout, cfg)
case environmentCommand.Used:
for _, e := range environment {
fmt.Fprintf(stdout, "%s\n", e)
}
return nil
default:
flaggy.ShowHelp("")
return nil
}
}
func setSource(stdout io.Writer, cfg *Config) error {
if cfg.SourceDir == "" {
return errors.New("source directory is required")
}
g, err := git.Open(cfg.SourceDir)
switch err != nil {
case true:
if !errors.Is(err, os.ErrNotExist) {
return err
}
switch cfg.SourceRepo == "" {
case true:
return fmt.Errorf("source directory not found: %s", cfg.SourceDir)
default:
if err := git.Clone(
cfg.SourceRepo, cfg.SourceDir,
git.CloneOptions{Depth: 1, Branch: "main"}, // Speed up the clone.
); err != nil {
switch strings.Contains(err.Error(), "ssh: Could not resolve hostname") {
case true:
fmt.Fprintln(stdout, "🚨 Could not connect to remote repository.")
return fmt.Errorf("source directory not found: %s", cfg.SourceDir)
default:
return err
}
}
}
default:
if _, err := g.RemoteGetURL("origin"); err == nil {
if err := g.Fetch(); err != nil {
switch strings.Contains(err.Error(), "ssh: Could not resolve hostname") {
case true:
fmt.Fprintln(stdout, "🚨 Could not connect to remote repository.")
return nil
default:
return err
}
}
if err := g.Pull(); err != nil {
return err
}
} else {
e := err.Error()
if !strings.Contains(e, "not a git repository") &&
!strings.Contains(e, "No such remote") {
return err
}
}
}
return nil
}
func addFeature(stdout io.Writer, cfg *Config, args ...string) error {
dest := "."
dest, err := filepath.Abs(dest)
if err != nil {
return err
}
asd, err := getArchetypesFolder(cfg.SourceDir, cfg.ArchetypesFolder)
if err != nil {
return err
}
ad, err := getArchetypeFolder(asd, cfg.Archetype)
if err != nil {
return err
}
tf, err := getTransformationFile(cfg.Transformation)
if err != nil {
return err
}
fmt.Fprintf(stdout, "🌱 Adding '%s' feature using '%s' archetype.\n", cfg.FeatureName, cfg.Archetype)
tf = filepath.Join(ad, tf)
fi, err := os.Stat(tf)
if err != nil {
return err
}
if fi.IsDir() {
return fmt.Errorf("invalid transformation file: %s", tf)
}
fmt.Fprintf(stdout, "📦 Using transformation file: %s\n", tf)
gs, err := gitstat.Get()
if err != nil {
return err
}
if gs.Dirty && !cfg.Force {
return errors.New("git repository is dirty")
}
b, err := os.ReadFile(tf)
if err != nil {
return err
}
if err := generator.OverlayGenerate(tf, ad, dest, getFeatureArgs(b, cfg, args), log.NewZeroLogger("warn")); err != nil {
return err
}
fmt.Fprintf(stdout, "🎉 Feature '%s' added.\n", cfg.FeatureName)
return nil
}
func list(stdout io.Writer, cfg *Config) error {
ad, err := getArchetypesFolder(cfg.SourceDir, cfg.ArchetypesFolder)
if err != nil {
return err
}
as, err := getArchetypes(ad)
if err != nil {
return err
}
for _, a := range as {
ts, err := getTransformations(filepath.Join(ad, a))
if err != nil {
return err
}
if len(ts) == 0 {
continue
}
fmt.Fprintf(stdout, "📦 Archetype: %s\n", a)
if len(ts) == 1 && ts[0] == defaultTransformation {
continue
}
for _, t := range ts {
fmt.Fprintf(stdout, " 📄 Transformation: %s\n", t)
}
}
return nil
}
func getArchetypesFolder(dir, archetypes string) (string, error) {
if dir == "" {
return "", errors.New("undefined dir")
}
if archetypes == "" {
return "", errors.New("undefined archetypes")
}
ad := filepath.Join(dir, archetypes)
fi, err := os.Stat(ad)
if err != nil {
return "", err
}
if !fi.IsDir() {
return "", fmt.Errorf("invalid archetypes folder: %s", ad)
}
return ad, nil
}
func getArchetypeFolder(dir, archetype string) (string, error) {
if dir == "" {
return "", errors.New("undefined dir")
}
if archetype == "" {
return "", errors.New("undefined archetype")
}
ad := filepath.Join(dir, archetype)
fi, err := os.Stat(ad)
if err != nil {
return "", err
}
if !fi.IsDir() {
return "", fmt.Errorf("invalid archetype folder: %s", ad)
}
return ad, nil
}
func getTransformationFile(transformation string) (string, error) {
if transformation == "" {
return "", errors.New("undefined transformation")
}
return fmt.Sprintf("%s%s.%s", transformationPrefix, transformation, transformationExt), nil
}
func getArchetypes(dir string) ([]string, error) {
if dir == "" {
return nil, errors.New("undefined dir")
}
var as []string
f, err := os.Open(dir)
if err != nil {
return nil, err
}
defer f.Close()
entries, err := f.Readdirnames(-1)
if err != nil {
return nil, err
}
for _, f := range entries {
fi, err := os.Stat(filepath.Join(dir, f))
if err != nil {
return nil, err
}
if fi.IsDir() {
as = append(as, f)
}
}
return as, nil
}
func getTransformations(dir string) ([]string, error) {
if dir == "" {
return nil, errors.New("undefined dir")
}
var ts []string
f, err := os.Open(dir)
if err != nil {
return nil, err
}
defer f.Close()
entries, err := f.Readdirnames(-1)
if err != nil {
return nil, err
}
for _, f := range entries {
if strings.HasPrefix(f, transformationPrefix) && strings.HasSuffix(f, transformationExt) {
t := strings.TrimSuffix(strings.TrimPrefix(f, transformationPrefix), "."+transformationExt)
ts = append(ts, t)
}
}
return ts, nil
}
func getFeatureArgs(transformation []byte, cfg *Config, args []string) []string {
var fn string
if bytes.Contains(transformation, []byte("- id: "+featureNameID)) {
fn = cfg.FeatureName
}
var mod string
if bytes.Contains(transformation, []byte("- id: "+goModNameID)) {
goModBytes, err := os.ReadFile("go.mod")
if err == nil {
mod = modfile.ModulePath(goModBytes)
}
}
as := []string{}
if fn != "" {
as = append(as, []string{"--" + featureNameID, fn}...)
}
if mod != "" {
as = append(as, []string{"--" + goModNameID, mod}...)
}
var removeNext bool
for _, a := range args {
switch {
case removeNext:
removeNext = false
continue
case a == "--"+featureNameID, a == "--"+goModNameID:
removeNext = true
continue
case strings.HasPrefix(a, "--"+featureNameID+"="), strings.HasPrefix(a, "--"+goModNameID+"="):
continue
default:
as = append(as, a)
}
}
return as
}