-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgo_handler.go
More file actions
429 lines (370 loc) · 12.9 KB
/
go_handler.go
File metadata and controls
429 lines (370 loc) · 12.9 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
package devflow
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/tinywasm/gorun"
)
// Go handler for Go operations
type Go struct {
rootDir string
git GitClient // Interface for better testing
log func(...any)
consoleOutput func(string) // output for ConsoleFilter (fmt.Println by default)
backup *DevBackup
retryDelay time.Duration
retryAttempts int
}
// GoVersion reads the Go version from the go.mod file in the current directory.
// It returns the version string (e.g., "1.18") or an empty string if not found.
func (g *Go) GoVersion() (string, error) {
data, err := os.ReadFile("go.mod")
if err != nil {
return "", err
}
re := regexp.MustCompile(`^go\s+(\d+\.\d+)`)
matches := re.FindStringSubmatch(string(data))
if len(matches) > 1 {
return matches[1], nil
}
return "", nil
}
// NewGo creates a new Go handler and verifies Go installation
func NewGo(gitHandler GitClient) (*Go, error) {
// Verify go installation
if _, err := RunCommandSilent("go", "version"); err != nil {
return nil, fmt.Errorf("go is not installed or not in PATH: %w", err)
}
return &Go{
rootDir: ".",
git: gitHandler,
backup: NewDevBackup(),
log: func(...any) {}, // default no-op
consoleOutput: func(s string) { fmt.Println(s) }, // real-time test output
retryDelay: 5 * time.Second,
retryAttempts: 3,
}, nil
}
// SetRetryConfig sets the retry configuration for network operations
func (g *Go) SetRetryConfig(delay time.Duration, attempts int) {
g.retryDelay = delay
g.retryAttempts = attempts
}
// SetRootDir sets the root directory for Go operations
func (g *Go) SetRootDir(path string) {
g.rootDir = path
}
// SetLog sets the logger function
func (g *Go) SetLog(fn func(...any)) {
if fn != nil {
g.log = fn
if g.git != nil {
g.git.SetLog(fn)
}
if g.backup != nil {
g.backup.SetLog(fn)
}
}
}
// SetConsoleOutput sets the function for console output (used by ConsoleFilter)
func (g *Go) SetConsoleOutput(fn func(string)) {
g.consoleOutput = fn
}
// GetLog returns the logger function
func (g *Go) GetLog() func(...any) {
return g.log
}
// GetGit returns the git client
func (g *Go) GetGit() GitClient {
return g.git
}
// Push executes the complete workflow for Go projects
// Parameters:
//
// message: Commit message
// tag: Optional tag
// skipTests: If true, skips tests
// skipRace: If true, skips race tests
// skipDependents: If true, skips updating dependent modules
// skipBackup: If true, skips backup
// skipTag: If true, skips tag generation and pushes without tags
// searchPath: Path to search for dependent modules (default: "..")
func (g *Go) Push(message, tag string, skipTests, skipRace, skipDependents, skipBackup, skipTag bool, searchPath string) (PushResult, error) {
// Validate message
if err := ValidateCommitMessage(message); err != nil {
return PushResult{}, err
}
message = FormatCommitMessage(message)
if searchPath == "" {
searchPath = ".."
}
summary := []string{}
// 0. Early exit if nothing to push
hasPending, _ := g.git.HasPendingChanges()
if !hasPending {
return PushResult{Summary: "Nothing to push"}, nil
}
// UNIVERSAL: If not a Go project, skip Go-specific steps
if !g.ModExists() {
var res PushResult
var err error
if skipTag {
if err := g.git.Add(); err != nil {
return PushResult{}, fmt.Errorf("git add failed: %w", err)
}
committed, _ := g.git.Commit(message)
pulled, pushErr := g.git.PushWithoutTags()
err = pushErr
res.Summary = "Pushed ✅"
if pulled {
res.Summary = "🔄 Pulled remote changes, " + res.Summary
}
if !committed && err == nil {
res.Summary = "No changes to commit"
}
} else {
res, err = g.git.Push(message, tag)
}
if !skipBackup && err == nil {
if _, backupErr := g.backup.Run(); backupErr != nil {
res.Summary += fmt.Sprintf(", ❌ backup failed: %v", backupErr)
}
}
return res, err
}
// 1. Verify go.mod
if err := g.Verify(); err != nil {
return PushResult{}, fmt.Errorf("go mod verify failed: %w", err)
}
// 2. Run tests (if not skipped)
if !skipTests {
testSummary, err := g.Test([]string{}, skipRace, 0, false, false) // Empty slice = full test suite, 0 = default timeout, false = allow cache, false = runAll
if err != nil {
return PushResult{}, fmt.Errorf("tests failed: %w", err)
}
summary = append(summary, testSummary)
} else {
summary = append(summary, "Tests skipped")
}
// 3. Execute git push workflow
var pushResult PushResult
var err error
if skipTag {
if err := g.git.Add(); err != nil {
return PushResult{}, fmt.Errorf("git add failed: %w", err)
}
committed, commitErr := g.git.Commit(message)
if commitErr != nil {
return PushResult{}, fmt.Errorf("git commit failed: %w", commitErr)
}
pulled, pushErr := g.git.PushWithoutTags()
if pushErr != nil {
return PushResult{}, fmt.Errorf("push failed: %w", pushErr)
}
pushResult.Summary = "Pushed ✅"
if pulled {
pushResult.Summary = "🔄 Pulled remote changes, " + pushResult.Summary
}
if !committed {
pushResult.Summary = "No changes to commit"
}
} else {
pushResult, err = g.git.Push(message, tag)
if err != nil {
return PushResult{}, fmt.Errorf("push workflow failed: %w", err)
}
}
summary = append(summary, pushResult.Summary)
// 4. Use the tag that was actually created and pushed
createdTag := pushResult.Tag
// 4.5 Install binaries (if cmd exists) — streamed to console, not summary
if createdTag != "" {
if err := g.Install(createdTag); err != nil {
summary = append(summary, fmt.Sprintf("Warning: install failed: %v", err))
}
}
// 5. Get module name
modulePath, err := g.GetModulePath()
if err != nil {
summary = append(summary, fmt.Sprintf("Warning: could not get module path: %v", err))
return PushResult{Summary: strings.Join(summary, ", "), Tag: createdTag}, nil
}
// 6. Update dependent modules (only if we have a valid tag)
if !skipDependents && createdTag != "" {
if err := g.UpdateDependents(modulePath, createdTag, searchPath); err != nil {
summary = append(summary, fmt.Sprintf("Warning: failed to scan dependents: %v", err))
}
}
// 7. Execute backup (asynchronous, non-blocking)
if !skipBackup {
if backupMsg, err := g.backup.Run(); err != nil {
summary = append(summary, fmt.Sprintf("❌ backup failed to start: %v", err))
} else if backupMsg != "" {
summary = append(summary, backupMsg)
}
}
return PushResult{Summary: strings.Join(summary, ", "), Tag: createdTag}, nil
}
// Publish satisfies the Publisher interface
func (g *Go) Publish(message, tag string, skipTests, skipRace, skipDependents, skipBackup, skipTag bool) (PushResult, error) {
return g.Push(message, tag, skipTests, skipRace, skipDependents, skipBackup, skipTag, "..")
}
// UpdateDependentModule updates a dependent module and optionally pushes it
// This is called for each module that depends on the one we just published
// UpdateDependentModule updates a specific dependent module
// It modifies go.mod to require the new version and runs go mod tidy
func (g *Go) UpdateDependentModule(depDir, modulePath, version string) (string, error) {
depName := filepath.Base(depDir)
// 1-2. Load and modify go.mod
modFile := filepath.Join(depDir, "go.mod")
gomod := NewGoModHandler()
gomod.SetRootDir(depDir)
// No error check needed for creation, but methods will fail if file missing
// Check/Load explicitly if we want to fail fast?
// But current flow relied on NewGoModHandler returning error.
// Since we moved loading to methods, we can't fail fast here unless we call something.
// But RemoveReplace returns bool.
// Save() returns error if write fails.
// Maybe we should just proceed.
// The original code returned error if file not found.
// Let's verify file existence manually?
if _, err := os.Stat(modFile); err != nil {
return "", fmt.Errorf("failed to load go.mod: %w", err)
}
gomod.RemoveReplace(modulePath)
// 3. Save changes (GoModFile saves to its absolute path)
if err := gomod.Save(); err != nil {
return "", fmt.Errorf("failed to save go.mod: %w", err)
}
// 4. Smart Update Logic
currentVer, err := g.GetCurrentVersion(depDir, modulePath)
if err == nil {
if CompareVersions(currentVer, version) >= 0 {
return fmt.Sprintf("already up-to-date (%s)", currentVer), nil
}
}
// 4.1 Run go get WITHOUT -u using explicit directory context
target := fmt.Sprintf("%s@%s", modulePath, version)
// Note: We use RunCommandWithRetryInDir here
if _, err := RunCommandWithRetryInDir(depDir, "go", []string{"get", target}, g.retryAttempts, g.retryDelay); err != nil {
return "", fmt.Errorf("go get failed after retries: %w", err)
}
// 5. Run go mod tidy in the specific directory
// Note: GoModFile.RunTidy() uses a separate exec.Command with Dir set, but to be consistent
// and ensure we don't rely on side-effects, we can call it directly or ensure RunTidy works safely.
// Looking at GoModFile.RunTidy, it uses cmd.Dir = filepath.Dir(m.path), so it IS SAFE.
// However, let's explicitely use our safe helper if we prefer, OR trust RunTidy.
// The original code called gomod.RunTidy(). Let's stick to using RunCommandInDir for explicit control if gomod.RunTidy logic is hidden.
// But gomod.RunTidy IS safe (it takes absolute path from constructor).
// Let's use RunCommandInDir for consistency with 'go get' above to be 100% sure we control the execution.
if _, err := RunCommandInDir(depDir, "go", "mod", "tidy"); err != nil {
return "", fmt.Errorf("go mod tidy failed: %w", err)
}
// 6. Check for other replaces
if gomod.HasOtherReplaces(modulePath) {
g.consoleOutput(fmt.Sprintf("📦 %s → skip (other replaces) ⏭", depName))
return "updated (other replaces exist, manual push required)", nil
}
// 7. Run tests in the dependent's directory
if output, err := RunCommandInDir(depDir, "gotest", "-t", "60", "-no-cache"); err != nil {
cause := extractFirstFailure(output)
g.consoleOutput(fmt.Sprintf("📦 %s → %s ❌", depName, cause))
return "", fmt.Errorf("tests failed: %w", err)
}
// 8. Push the dependent module (skipTests=true since we already tested)
git, err := NewGit()
if err != nil {
return "", fmt.Errorf("git init failed: %w", err)
}
git.SetRootDir(depDir)
depHandler, err := NewGo(git)
if err != nil {
return "", fmt.Errorf("go handler init failed: %w", err)
}
depHandler.SetRootDir(depDir)
commitMsg := fmt.Sprintf("deps: update %s to %s", filepath.Base(modulePath), version)
_, err = depHandler.Push(commitMsg, "", true, true, true, true, true, "")
if err != nil {
g.consoleOutput(fmt.Sprintf("📦 %s → ❌ push failed", depName))
return "", fmt.Errorf("push failed: %w", err)
}
g.consoleOutput(fmt.Sprintf("📦 %s → updated ✅", depName))
return fmt.Sprintf("updated to %s", version), nil
}
// GetCurrentVersion returns the current version of a dependency in a module
func (g *Go) GetCurrentVersion(moduleDir, dependencyPath string) (string, error) {
// Use go list -m -json dependencyPath directly in moduleDir
output, err := RunCommandInDir(moduleDir, "go", "list", "-m", "-json", dependencyPath)
if err != nil {
return "", err
}
var mod struct {
Version string `json:"Version"`
}
if err := json.Unmarshal([]byte(output), &mod); err != nil {
return "", err
}
return mod.Version, nil
}
// extractFirstFailure returns a short failure label from gotest output
func extractFirstFailure(output string) string {
if strings.Contains(output, "vet ❌") {
return "vet"
}
if strings.Contains(output, "timeout:") {
return "timeout"
}
if strings.Contains(output, "❌") {
return "tests"
}
return "failed"
}
// Install builds and installs all commands in the cmd/ directory
// It injects the version using ldflags if provided
func (g *Go) Install(version string) error {
cmdDir := filepath.Join(g.rootDir, "cmd")
if _, err := os.Stat(cmdDir); os.IsNotExist(err) {
return nil // No cmd directory, skip silently
}
entries, err := os.ReadDir(cmdDir)
if err != nil {
return fmt.Errorf("failed to read cmd directory: %w", err)
}
var commands []string
for _, entry := range entries {
if entry.IsDir() {
commands = append(commands, entry.Name())
}
}
if len(commands) == 0 {
return nil // No commands found
}
ldflags := ""
actualVersion := version
if actualVersion == "" && g.git != nil {
if tag, err := g.git.GetLatestTag(); err == nil && tag != "" {
actualVersion = tag
}
}
if actualVersion != "" {
ldflags = fmt.Sprintf("-ldflags=-X main.Version=%s", actualVersion)
}
for _, cmd := range commands {
_ = gorun.StopApp(cmd) // Kill any running instance before install
pkg := "./cmd/" + cmd
args := []string{"install"}
if ldflags != "" {
args = append(args, ldflags)
}
args = append(args, pkg)
if _, err := RunCommandInDir(g.rootDir, "go", args...); err != nil {
return fmt.Errorf("failed to install %s: %w", cmd, err)
}
}
g.consoleOutput(fmt.Sprintf("✅ Installed: %s", strings.Join(commands, ", ")))
return nil
}