-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
500 lines (445 loc) · 12.6 KB
/
main.go
File metadata and controls
500 lines (445 loc) · 12.6 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package main
import (
"bufio"
"database/sql"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "modernc.org/sqlite"
"slices"
"github.com/xlc-dev/nova/nova"
"github.com/xlc-dev/nova/templates"
)
var logo = " _ _\n" +
"| \\ | |\n" +
"| \\| | ___ __ __ __ _\n" +
"| . ` | / _ \\\\ \\ / // _` |\n" +
"| |\\ || (_) |\\ V /| (_| |\n" +
"|_| \\_| \\___/ \\_/ \\____|\n"
// projectGenerator holds the state and logic for creating a new project.
type projectGenerator struct {
projectName string
projectDir string
isVerbose bool
reader *bufio.Reader
// User choices
templateChoice string
dbAdapter string
useGit bool
useMakefile bool
}
// cleanupOnFailure removes the project directory if generation failed.
// Only call this if the directory was partially created.
func (g *projectGenerator) cleanupOnFailure() error {
if g.projectDir == "" {
return nil // Nothing to clean
}
if _, err := os.Stat(g.projectDir); os.IsNotExist(err) {
return nil // Already doesn't exist, no cleanup needed
}
if g.isVerbose {
fmt.Printf("Cleaning up partial project: %s\n", g.projectDir)
}
return os.RemoveAll(g.projectDir)
}
// newProjectGenerator is the constructor for our generator.
func newProjectGenerator(
projectName string,
isVerbose bool,
) (*projectGenerator, error) {
projectDir, err := filepath.Abs(projectName)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path: %w", err)
}
if _, err := os.Stat(projectDir); err == nil {
return nil, fmt.Errorf("directory '%s' already exists", projectName)
}
return &projectGenerator{
projectName: projectName,
projectDir: projectDir,
isVerbose: isVerbose,
reader: bufio.NewReader(os.Stdin),
}, nil
}
// run executes the full project generation workflow.
func (g *projectGenerator) run() error {
if err := os.MkdirAll(g.projectDir, 0755); err != nil {
return fmt.Errorf("failed to create project directory: %w", err)
}
fmt.Printf("Created directory: %s\n", g.projectDir)
if err := g.promptUserForChoices(); err != nil {
return err
}
if err := g.createFromTemplate(); err != nil {
return err
}
if err := g.initializeGoModule(); err != nil {
return err
}
if g.dbAdapter != "" {
if err := g.setupDatabase(); err != nil {
return err
}
}
if g.useGit {
if err := g.initializeGit(); err != nil {
return err
}
}
if g.useMakefile {
if err := g.createMakefile(); err != nil {
return err
}
}
return nil
}
// promptUserForChoices handles all interactive questions.
func (g *projectGenerator) promptUserForChoices() error {
var err error
// Template selection
templateOptions := []string{"minimal", "structured"}
g.templateChoice, err = g.ask(
"Select template (minimal, structured): ",
templateOptions,
)
if err != nil {
return err
}
dbAnswer, err := g.ask(
"Would you like to add a database? (y/n): ",
[]string{"y", "n"},
)
if err != nil {
return err
}
if dbAnswer == "y" {
adapterOptions := []string{"sqlite", "postgres", "mysql"}
g.dbAdapter, err = g.ask(
"Select database adapter (sqlite, postgres, mysql): ",
adapterOptions,
)
if err != nil {
return err
}
}
gitAnswer, err := g.ask(
"Initialize a git repository? (y/n): ",
[]string{"y", "n"},
)
if err != nil {
return err
}
g.useGit = (gitAnswer == "y")
makefileAnswer, err := g.ask(
"Would you like to add a Makefile? (y/n): ",
[]string{"y", "n"},
)
if err != nil {
return err
}
g.useMakefile = (makefileAnswer == "y")
return nil
}
// createFromTemplate executes the chosen template creation function.
func (g *projectGenerator) createFromTemplate() error {
createFns := map[string]func(projectDir string, isVerbose bool, dbAdapter string) error{
"minimal": templates.CreateMinimal,
"structured": templates.CreateStructured,
}
createFn, exists := createFns[g.templateChoice]
if !exists {
return fmt.Errorf("internal error: unknown template '%s'", g.templateChoice)
}
fmt.Println("Creating project from template...")
err := createFn(g.projectDir, g.isVerbose, g.dbAdapter)
if err != nil {
return fmt.Errorf("failed to create from template: %w", err)
}
return nil
}
// initializeGoModule runs `go mod init`, `go mod tidy`, and `go fmt`.
func (g *projectGenerator) initializeGoModule() error {
fmt.Println("Initializing Go module...")
if err := g.runCommand("go", "mod", "init", g.projectName); err != nil {
return fmt.Errorf("failed to run 'go mod init': %w", err)
}
if err := g.runCommand("go", "mod", "tidy"); err != nil {
return fmt.Errorf("failed to run 'go mod tidy': %w", err)
}
if err := g.runCommand("go", "fmt", "./..."); err != nil {
return fmt.Errorf("failed to run 'go fmt': %w", err)
}
return nil
}
// setupDatabase creates the .env file with the correct DATABASE_URL.
func (g *projectGenerator) setupDatabase() error {
dbConfig := map[string]string{
"sqlite": "DATABASE_URL=file:database.db?cache=shared&mode=rwc\n",
"postgres": "DATABASE_URL=postgres://user:password@localhost/dbname?sslmode=disable\n",
"mysql": "DATABASE_URL=mysql://user:password@tcp(127.0.0.1:3306)/dbname\n",
}
envURL, exists := dbConfig[g.dbAdapter]
if !exists {
return fmt.Errorf("internal error: unknown db adapter '%s'", g.dbAdapter)
}
fmt.Println("Creating .env file...")
envPath := filepath.Join(g.projectDir, ".env")
if err := os.WriteFile(envPath, []byte(envURL), 0644); err != nil {
return fmt.Errorf("failed to create .env file: %w", err)
}
return nil
}
// initializeGit creates a .gitignore file and runs `git init`.
func (g *projectGenerator) initializeGit() error {
fmt.Println("Initializing git repository...")
gitignore := fmt.Sprintf(`.DS_Store
Thumbs.db
*.exe
*.exe~
*.dll
*.so
*.dylib
.idea/
.vscode/
*~
*.swp
.env
*.db
%s
`, g.projectName)
gitignorePath := filepath.Join(g.projectDir, ".gitignore")
if err := os.WriteFile(gitignorePath, []byte(gitignore), 0644); err != nil {
return fmt.Errorf("failed to create .gitignore: %w", err)
}
if err := g.runCommand("git", "init"); err != nil {
return fmt.Errorf("failed to initialize git: %w", err)
}
fmt.Println("Git repository and .gitignore initialized successfully.")
return nil
}
// createMakefile generates and writes the Makefile.
func (g *projectGenerator) createMakefile() error {
fmt.Println("Creating Makefile...")
var buildTarget string
if g.templateChoice == "structured" {
buildTarget = fmt.Sprintf("./cmd/%s", g.projectName)
} else {
buildTarget = "."
}
makefileContent := fmt.Sprintf(`BINARY_NAME=%s
.PHONY: build clean fmt test help
default: build
build:
@go build -o $(BINARY_NAME) %s
clean:
@rm -f $(BINARY_NAME)
fmt:
@goimports -w .
@go fmt ./...
test:
@go test ./... -v
help:
@echo "Available Make targets:"
@echo " build : Build the Go application (default)"
@echo " clean : Remove the built binary ($(BINARY_NAME))"
@echo " fmt : Format Go source code (using goimports)"
@echo " test : Run Go tests"
@echo " help : Show this help message"
`, g.projectName, buildTarget)
makefile_path := filepath.Join(g.projectDir, "Makefile")
if err := os.WriteFile(makefile_path, []byte(makefileContent), 0644); err != nil {
return fmt.Errorf("failed to create Makefile: %w", err)
}
fmt.Println("Makefile created successfully.")
return nil
}
// runCommand is a helper to execute external commands in the project directory.
func (g *projectGenerator) runCommand(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Dir = g.projectDir
if g.isVerbose {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("command '%s %s' failed: %w", name, strings.Join(args, " "), err)
}
return nil
}
// ask is a generic helper for prompting the user and validating input.
func (g *projectGenerator) ask(
prompt string,
validOptions []string,
) (string, error) {
for {
fmt.Print(prompt)
input, err := g.reader.ReadString('\n')
if err != nil {
return "", fmt.Errorf("failed to read user input: %w", err)
}
input = strings.TrimSpace(strings.ToLower(input))
if slices.Contains(validOptions, input) {
return input, nil
}
fmt.Printf(
"Invalid input. Please choose one of: %v\n",
validOptions,
)
}
}
func main() {
config := &nova.CLI{
Name: "Nova",
Version: "0.0.1",
Description: "A modern do-it-all Golang framework to create REST APIs with ease.",
GlobalFlags: []nova.Flag{
&nova.BoolFlag{
Name: "verbose",
Aliases: []string{"V"},
Usage: "Enable verbose output",
},
},
Commands: []*nova.Command{
{
Name: "gendoc",
Usage: "Generate markdown reference docs from Go code",
Description: "Parses Go source comments in a specified directory and outputs Markdown documentation. This is made for Nova's own use, but you can try it out if you like :)",
Flags: []nova.Flag{
&nova.StringFlag{
Name: "input",
Default: "./nova",
Usage: "Directory containing the Go package source files",
},
&nova.StringFlag{
Name: "output",
Aliases: []string{"o"},
Default: "reference.md",
Usage: "Output file for the generated markdown",
},
},
Action: func(ctx *nova.Context) error {
inputDir := ctx.String("input")
outputFile := ctx.String("output")
err := generateReferenceMarkdown(inputDir, outputFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error generating docs: %v\n", err)
return err
}
return nil
},
},
{
Name: "migrate",
Usage: "Manages database migrations (up, down, new)",
Description: "Applies pending migrations (up), rolls back migrations (down), or creates a new migration file (new).",
ArgsUsage: "<up|down|new> [steps|migration_name]",
Action: func(ctx *nova.Context) error {
// Load environment variables from a .env file if it exists
if err := nova.LoadDotenv(); err != nil {
log.Fatalf("Error loading .env: %v", err)
}
// Read the full DSN from DATABASE_URL
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
return fmt.Errorf("DATABASE_URL environment variable is not set")
}
args := ctx.Args()
if len(args) < 1 {
return fmt.Errorf("expected a migration action: up, down, or new")
}
action := args[0]
// Determine the driver based on the DSN prefix
var driver string
if strings.HasPrefix(dsn, "postgres://") {
driver = "pq"
} else if strings.HasPrefix(dsn, "mysql://") {
driver = "mysql"
} else if strings.HasPrefix(dsn, "file:") || strings.HasSuffix(dsn, ".db") {
driver = "sqlite"
} else {
return fmt.Errorf("unsupported DSN: %s", dsn)
}
db, err := sql.Open(driver, dsn)
if err != nil {
return err
}
defer db.Close()
switch action {
case "up":
steps := 0
if len(args) > 1 {
steps, err = strconv.Atoi(args[1])
if err != nil {
return fmt.Errorf("invalid steps: %w", err)
}
}
return nova.MigrateUp(db, steps)
case "down":
steps := 1
if len(args) > 1 {
steps, err = strconv.Atoi(args[1])
if err != nil {
return fmt.Errorf("invalid steps: %w", err)
}
}
return nova.MigrateDown(db, steps)
case "new":
if len(args) < 2 {
return fmt.Errorf("migration name required for 'new' action")
}
migrationName := args[1]
return nova.CreateNewMigration(migrationName)
default:
return fmt.Errorf("unknown migration action: %s", action)
}
},
},
{
Name: "new",
Aliases: []string{"n"},
Usage: "Creates a new project",
Description: "Creates a new project directory with the basic structure.",
ArgsUsage: "<project-name>",
Action: func(ctx *nova.Context) (err error) {
if len(ctx.Args()) != 1 {
return fmt.Errorf("expected exactly one argument: <project-name>")
}
projectName := ctx.Args()[0]
g, err := newProjectGenerator(projectName, ctx.Bool("verbose"))
if err != nil {
return err
}
defer func() {
if err != nil {
cleanupErr := g.cleanupOnFailure()
if cleanupErr != nil && g.isVerbose {
fmt.Printf("Warning: Cleanup failed: %v\n", cleanupErr)
}
}
}()
err = g.run()
if err != nil {
return fmt.Errorf("failed to create project: %w", err)
}
fmt.Printf("\nProject '%s' created successfully.\n", projectName)
return nil
},
},
},
}
cli, err := nova.NewCLI(config)
if err != nil {
log.Fatalf("Failed to initialize CLI: %v", err)
}
fmt.Println(logo)
err = cli.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}