-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
310 lines (265 loc) · 7.22 KB
/
Copy pathmain.go
File metadata and controls
310 lines (265 loc) · 7.22 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
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/AeonDave/goahead/internal"
)
func main() {
if isToolexecMode() {
toolexecManager := internal.NewToolexecManager()
toolexecManager.RunAsToolexec()
return
}
// Check for subcommands: goahead build, goahead run, goahead test
if len(os.Args) >= 2 {
switch os.Args[1] {
case "build", "run", "test":
runGoCommandWithCodegen(os.Args[1], os.Args[2:])
return
}
}
// If no arguments are provided, show help/usage instead of running codegen
if len(os.Args) == 1 {
showHelp()
return
}
config := parseFlags()
if config.Help {
showHelp()
return
}
if config.Version {
fmt.Printf("goahead version %s\n", internal.Version)
return
}
if config.Verbose {
fmt.Printf("Running goahead in standalone mode\n")
fmt.Printf("Processing directory: %s\n", config.Dir)
}
if err := internal.RunCodegen(config.Dir, config.Verbose); err != nil {
log.Fatalf("Error: %v", err)
}
}
// runGoCommandWithCodegen runs codegen first, then executes go build/run/test
func runGoCommandWithCodegen(command string, args []string) {
verbose := os.Getenv("GOAHEAD_VERBOSE") == "1"
codegenDir := "."
// Parse goahead-specific flags from args
var goArgs []string
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "-verbose" || arg == "--verbose" {
verbose = true
continue
}
if arg == "-dir" || arg == "--dir" {
if i+1 < len(args) {
codegenDir = args[i+1]
i++ // skip next arg
continue
}
}
if strings.HasPrefix(arg, "-dir=") || strings.HasPrefix(arg, "--dir=") {
codegenDir = strings.SplitN(arg, "=", 2)[1]
continue
}
goArgs = append(goArgs, arg)
}
// If no explicit -dir, try to determine from package path
if codegenDir == "." {
for i, arg := range goArgs {
// Look for package path arguments (not flags)
if !strings.HasPrefix(arg, "-") && (strings.HasPrefix(arg, "./") || arg == "." || strings.HasSuffix(arg, "...")) {
// Extract directory from pattern like ./cmd/... or ./pkg
dir := strings.TrimSuffix(arg, "/...")
dir = strings.TrimSuffix(dir, "...")
if dir == "" || dir == "." {
dir = "."
}
// For patterns like ./... we want to process from current dir
if strings.Contains(goArgs[i], "...") {
codegenDir = "."
} else {
codegenDir = dir
}
break
}
}
}
if verbose {
fmt.Fprintf(os.Stderr, "[goahead] Running codegen in %s before 'go %s'\n", codegenDir, command)
}
// Run codegen first
if err := internal.RunCodegen(codegenDir, verbose); err != nil {
log.Fatalf("[goahead] Codegen failed: %v", err)
}
// Now run go command WITHOUT toolexec
goCmd := append([]string{command}, goArgs...)
cmd := exec.Command("go", goCmd...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if verbose {
fmt.Fprintf(os.Stderr, "[goahead] Running: go %s\n", strings.Join(goCmd, " "))
}
if err := cmd.Run(); err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
os.Exit(exitErr.ExitCode())
}
os.Exit(1)
}
}
func isToolexecMode() bool {
if len(os.Args) < 2 {
return false
}
// In toolexec mode, Go passes the tool path as an argument. Scan for the first
// non-flag argument and accept any executable that looks like a Go tool.
for i := 1; i < len(os.Args); i++ {
arg := os.Args[i]
if strings.HasPrefix(arg, "-") {
continue
}
if looksLikeGoTool(arg) {
return true
}
}
return false
}
func looksLikeGoTool(arg string) bool {
if strings.Contains(arg, "go"+string(os.PathSeparator)+"pkg"+string(os.PathSeparator)+"tool") {
return true
}
base := filepath.Base(arg)
if strings.HasSuffix(strings.ToLower(base), ".exe") {
base = base[:len(base)-4]
}
switch strings.ToLower(base) {
case "compile", "link", "asm", "cgo", "pack", "buildid",
"addr2line", "api", "cover", "dist", "doc", "fix", "nm",
"objdump", "pprof", "test2json", "trace", "vet":
return true
default:
return false
}
}
func parseFlags() *internal.Config {
config := &internal.Config{}
flag.StringVar(&config.Dir, "dir", ".", "Directory to process")
flag.BoolVar(&config.Verbose, "verbose", false, "Enable verbose output")
flag.BoolVar(&config.Help, "help", false, "Show help")
flag.BoolVar(&config.Version, "version", false, "Show version")
flag.Parse()
return config
}
func showHelp() {
const boxInnerWidth = 79
center := func(s string, width int) string {
r := []rune(s)
if len(r) >= width {
return string(r[:width])
}
pad := width - len(r)
left := pad / 2
right := pad - left
return strings.Repeat(" ", left) + s + strings.Repeat(" ", right)
}
shortVersionForBanner := func(version string) string {
version = strings.TrimSpace(version)
if version == "" {
return "dev"
}
if version == "(devel)" {
return "dev"
}
// Preserve a dirty marker, but drop long pseudo-version details.
meta := ""
if i := strings.Index(version, "+"); i >= 0 {
meta = version[i:]
version = version[:i]
}
if meta != "+dirty" {
// Only keep a concise dirty marker in the banner.
meta = ""
}
// Trim Go pseudo-version suffixes like:
// v0.1.1-0.20260121133307-33bc43fdf900
// keeping just v0.1.1
if i := strings.Index(version, "-0."); i >= 0 {
// Ensure it looks like -0.<14digits>-<hash>
if len(version) >= i+3+14 {
isDigits := true
for _, c := range version[i+3 : i+3+14] {
if c < '0' || c > '9' {
isDigits = false
break
}
}
if isDigits {
version = version[:i]
}
}
}
if version == "" {
version = "dev"
}
return version + meta
}
short := shortVersionForBanner(internal.Version)
if !strings.HasPrefix(short, "v") {
short = "v" + short
}
title := "GOAHEAD " + short
header := "╔" + strings.Repeat("═", boxInnerWidth) + "╗\n" +
"║" + center(title, boxInnerWidth) + "║\n" +
"║" + center("Compile-Time Code Generation for Go", boxInnerWidth) + "║\n" +
"╚" + strings.Repeat("═", boxInnerWidth) + "╝\n"
body := `
Replace placeholder comments with computed values at build time.
INSTALL
go install github.com/AeonDave/goahead@latest
USAGE
Subcommands (recommended for CGO):
goahead build ./... Process + build
goahead run ./cmd/app Process + run
goahead test ./... Process + test
Toolexec mode:
go build -toolexec="goahead" ./...
Standalone (process only):
goahead -dir=./mypackage
QUICK START
1. Create a helper file (helpers.go):
//go:build exclude
//go:ahead functions
package helpers
func welcome(name string) string { return "Hello, " + name }
2. Use placeholders in your code (main.go):
package main
//:welcome:"gopher"
var greeting = ""
3. Build with goahead:
goahead build ./...
Result: greeting becomes "Hello, gopher"
OPTIONS
-dir <path> Directory to process (default: current)
-verbose Enable verbose output
-help Show this help
-version Show version
ENVIRONMENT
GOAHEAD_VERBOSE=1 Enable verbose output
DOCUMENTATION
https://github.com/AeonDave/goahead
`
// The raw string above is indented in source code; convert leading tabs into
// spaces so the CLI output is aligned consistently across terminals.
body = strings.NewReplacer(
"\n\t\t", "\n ",
"\n\t", "\n ",
).Replace(body)
fmt.Print("\n" + header + body)
}