-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_handler.go
More file actions
588 lines (504 loc) · 15.8 KB
/
git_handler.go
File metadata and controls
588 lines (504 loc) · 15.8 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
package devflow
import (
"fmt"
"strconv"
"strings"
)
func isNonFastForwardError(output string) bool {
return strings.Contains(output, "non-fast-forward") ||
strings.Contains(output, "[rejected]")
}
// Git handler for Git operations
type Git struct {
rootDir string
shouldWrite func() bool
log func(...any)
authRetrier GitHubAuthenticator
}
// NewGit creates a new Git handler and verifies git is available
func NewGit() (*Git, error) {
// Verify git installation
if _, err := RunCommandSilent("git", "--version"); err != nil {
return nil, fmt.Errorf("git is not installed or not in PATH: %w", err)
}
return &Git{
rootDir: "",
shouldWrite: func() bool { return false },
log: func(...any) {}, // default no-op
}, nil
}
// run executes a command in the handler's root directory
func (g *Git) run(name string, args ...string) (string, error) {
if g.rootDir != "" && g.rootDir != "." {
return RunCommandInDir(g.rootDir, name, args...)
}
return RunCommand(name, args...)
}
// runSilent executes a command silently in the handler's root directory
func (g *Git) runSilent(name string, args ...string) (string, error) {
if g.rootDir != "" && g.rootDir != "." {
return RunCommandInDir(g.rootDir, name, args...)
}
return RunCommandSilent(name, args...)
}
// SetRootDir sets the root directory for git operations
func (g *Git) SetRootDir(path string) {
g.rootDir = path
}
// SetShouldWrite sets a function that determines if Git write operations
// (like updating .gitignore) should be allowed.
func (g *Git) SetShouldWrite(f func() bool) {
g.shouldWrite = f
}
// SetLog sets the logger function
func (g *Git) SetLog(fn func(...any)) {
if fn != nil {
g.log = fn
}
}
// SetAuthRetrier injects an authenticator to use for auto-recovery on access errors
func (g *Git) SetAuthRetrier(a GitHubAuthenticator) {
g.authRetrier = a
}
// CheckRemoteAccess verifies connectivity to the remote repository.
// If an auth error is detected and an authRetrier is configured, it triggers
// the Device Flow auth automatically and retries once.
func (g *Git) CheckRemoteAccess() error {
_, err := g.runSilent("git", "ls-remote", "origin")
if err == nil {
return nil
}
isAuthErr := strings.Contains(err.Error(), "Authentication failed") ||
strings.Contains(err.Error(), "Could not read from remote repository")
if isAuthErr && g.authRetrier != nil {
g.log("🔑 Access denied. Restarting authentication...")
if authErr := g.authRetrier.EnsureGitHubAuth(); authErr != nil {
return fmt.Errorf("❌ authentication failed: %w", authErr)
}
// Retry once after successful re-auth
if _, retryErr := g.runSilent("git", "ls-remote", "origin"); retryErr != nil {
return fmt.Errorf("❌ remote access denied after re-authentication: %w", retryErr)
}
return nil
}
if isAuthErr {
return fmt.Errorf("❌ Authentication failed. Please check your git credentials or use 'git push' manually to authenticate")
}
if strings.Contains(err.Error(), "Could not resolve host") {
return fmt.Errorf("❌ Network error. Please check your internet connection")
}
if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "does not exist") {
return fmt.Errorf("❌ Remote 'origin' not found. Please add a remote using 'git remote add origin <url>'")
}
return fmt.Errorf("❌ checking remote access failed: %w", err)
}
// PushResult contains the results of a Git push operation
type PushResult struct {
Summary string // Human-readable summary of operations performed
Tag string // The tag that was created and pushed
}
// Push executes the complete push workflow (add, commit, tag, push)
// Returns a PushResult and error if any.
func (g *Git) Push(message, tag string) (PushResult, error) {
// Validate message
if err := ValidateCommitMessage(message); err != nil {
return PushResult{}, err
}
message = FormatCommitMessage(message)
summary := []string{}
// 0. Verify remote access before doing anything destructive
if err := g.CheckRemoteAccess(); err != nil {
return PushResult{}, err
}
// 1. Git add
if err := g.Add(); err != nil {
return PushResult{}, fmt.Errorf("git add failed: %w", err)
}
// 2. Determine tag (provided or generated)
finalTag := tag
if finalTag == "" {
generatedTag, err := g.GenerateNextTag()
if err != nil {
return PushResult{}, fmt.Errorf("failed to generate tag: %w", err)
}
finalTag = generatedTag
}
// 3. Validate tag is greater than latest
latestTag, err := g.GetLatestTag()
if err == nil && latestTag != "" {
if CompareVersions(finalTag, latestTag) <= 0 {
return PushResult{}, fmt.Errorf("tag %s is not greater than latest tag %s", finalTag, latestTag)
}
}
// 4. Commit (only if there are changes)
committed, err := g.Commit(message)
if err != nil {
return PushResult{}, fmt.Errorf("git commit failed: %w", err)
}
// If no changes were committed, check if we're ahead of remote
// If so, we can still push existing commits without creating a tag
if !committed {
// Check if there are unpushed commits
ahead, err := g.IsAheadOfRemote()
if err != nil {
// Can't determine status, just return success without doing anything
return PushResult{
Summary: "No changes to commit",
Tag: "",
}, nil
}
if ahead {
// There are unpushed commits, push them without creating a new tag
pulled, err := g.PushWithoutTags()
if err != nil {
return PushResult{}, fmt.Errorf("push failed: %w", err)
}
summary := "✅ Pushed existing commits"
if pulled {
summary = "🔄 Pulled remote changes, " + summary
}
return PushResult{Summary: summary, Tag: ""}, nil
}
// No changes and no unpushed commits
return PushResult{
Summary: "No changes to commit",
Tag: "",
}, nil
}
// 5. Create tag - if exists, keep incrementing until we find available one
maxAttempts := 100 // Prevent infinite loop
attempt := 0
for attempt < maxAttempts {
created, err := g.CreateTag(finalTag)
if err == nil && created {
// Success
summary = append(summary, fmt.Sprintf("✅ Tag: %s", finalTag))
break
}
// Tag exists, increment from current finalTag
g.log("Tag", finalTag, "already exists, trying next")
nextTag, err := g.IncrementTag(finalTag)
if err != nil {
return PushResult{}, fmt.Errorf("failed to increment tag: %w", err)
}
finalTag = nextTag
attempt++
}
if attempt >= maxAttempts {
return PushResult{}, fmt.Errorf("could not find available tag after %d attempts", maxAttempts)
}
// 5. Push commits and tag
pulled, err := g.PushWithTags(finalTag)
if err != nil {
return PushResult{}, fmt.Errorf("push failed: %w", err)
}
if pulled {
summary = append(summary, "🔄 Pulled remote changes")
}
summary = append(summary, "✅ Pushed ok")
return PushResult{Summary: strings.Join(summary, ", "), Tag: finalTag}, nil
}
// Add adds all changes to staging
func (g *Git) Add() error {
_, err := g.run("git", "add", ".")
return err
}
// HasChanges checks if there are staged changes
func (g *Git) HasChanges() (bool, error) {
// Check if HEAD exists
_, err := g.runSilent("git", "rev-parse", "HEAD")
if err != nil {
// No HEAD (fresh repo). Check if there are any files staged for initial commit.
out, err := g.runSilent("git", "status", "--porcelain")
if err != nil {
return false, err
}
if len(out) > 0 {
return true, nil
}
return false, nil
}
// Use Silent to avoid spamming logs for checks
// CRITICAL: We use --cached to only check what IS STAGED.
// This prevents git commit from failing with "nothing to commit" when
// there are unstaged changes.
_, err = g.runSilent("git", "diff-index", "--quiet", "--cached", "HEAD", "--")
if err != nil {
// If command fails (exit code 1), it means there are changes
return true, nil
}
return false, nil
}
// Commit creates a commit with the given message
// Returns true if a commit was created
func (g *Git) Commit(message string) (bool, error) {
hasChanges, err := g.HasChanges()
if err != nil {
return false, err
}
if !hasChanges {
return false, nil
}
_, err = g.run("git", "commit", "-m", message)
if err != nil {
return false, err
}
return true, nil
}
// GetLatestTag gets the latest tag
func (g *Git) GetLatestTag() (string, error) {
// Use version:refname sort to get the highest semver tag, not just
// the closest reachable tag from HEAD (which git describe does).
output, err := g.runSilent("git", "tag", "-l", "--sort=-version:refname")
if err != nil || output == "" {
return "", nil
}
// First line = highest version
if idx := strings.IndexByte(output, '\n'); idx != -1 {
return output[:idx], nil
}
return output, nil
}
// CreateTag creates a new tag
func (g *Git) CreateTag(tag string) (bool, error) {
exists, err := g.TagExists(tag)
if err != nil {
return false, err
}
if exists {
return false, fmt.Errorf("tag %s already exists", tag)
}
_, err = g.run("git", "tag", tag)
return true, err
}
// GenerateNextTag calculates the next semantic version
func (g *Git) GenerateNextTag() (string, error) {
latestTag, err := g.GetLatestTag()
if err != nil {
return "", err
}
if latestTag == "" {
return "v0.0.1", nil
}
parts := strings.Split(latestTag, ".")
if len(parts) < 3 {
return "", fmt.Errorf("invalid tag format: %s", latestTag)
}
lastNumStr := parts[len(parts)-1]
lastNum, err := strconv.Atoi(lastNumStr)
if err != nil {
return "", fmt.Errorf("invalid tag number: %s", lastNumStr)
}
parts[len(parts)-1] = strconv.Itoa(lastNum + 1)
newTag := strings.Join(parts, ".")
return newTag, nil
}
// IncrementTag increments a specific tag (e.g., v0.0.12 -> v0.0.13)
func (g *Git) IncrementTag(tag string) (string, error) {
if tag == "" {
return "v0.0.1", nil
}
parts := strings.Split(tag, ".")
if len(parts) < 3 {
return "", fmt.Errorf("invalid tag format: %s", tag)
}
lastNumStr := parts[len(parts)-1]
lastNum, err := strconv.Atoi(lastNumStr)
if err != nil {
return "", fmt.Errorf("invalid tag number: %s", lastNumStr)
}
parts[len(parts)-1] = strconv.Itoa(lastNum + 1)
newTag := strings.Join(parts, ".")
return newTag, nil
}
// TagExists checks if a tag exists
func (g *Git) TagExists(tag string) (bool, error) {
_, err := g.runSilent("git", "rev-parse", tag)
if err != nil {
return false, nil
}
return true, nil
}
// getCurrentBranch gets the current branch
func (g *Git) getCurrentBranch() (string, error) {
output, err := g.runSilent("git", "symbolic-ref", "--short", "HEAD")
if err != nil {
return "", fmt.Errorf("failed to get current branch: %w", err)
}
return output, nil
}
// HasUpstream checks if the branch has upstream
func (g *Git) HasUpstream() (bool, error) {
_, err := g.runSilent("git", "rev-parse", "--symbolic-full-name", "--abbrev-ref", "@{u}")
if err != nil {
return false, nil
}
return true, nil
}
// setUpstream configures upstream
func (g *Git) setUpstream(branch string) error {
_, err := g.run("git", "push", "--set-upstream", "origin", branch)
if err != nil {
return fmt.Errorf("failed to set upstream: %w", err)
}
return nil
}
// pushTag pushes a specific tag
func (g *Git) pushTag(tag string) error {
_, err := g.run("git", "push", "origin", tag)
if err != nil {
return fmt.Errorf("failed to push tag %s: %w", tag, err)
}
return nil
}
// autoPullRebase pulls changes from remote using rebase
func (g *Git) autoPullRebase() error {
branch, err := g.getCurrentBranch()
if err != nil {
return err
}
_, err = g.run("git", "pull", "origin", branch, "--rebase")
if err != nil {
return fmt.Errorf("auto-rebase failed after non-fast-forward push rejection.\n"+
"Please resolve conflicts manually, then retry gopush.\nError: %w", err)
}
return nil
}
// pushWithAutoRebase attempts to push and pulls/retries if it fails due to non-fast-forward
func (g *Git) pushWithAutoRebase(args ...string) (bool, error) {
output, pushErr := g.run("git", append([]string{"push"}, args...)...)
if pushErr == nil {
return false, nil
}
if !isNonFastForwardError(output) && !isNonFastForwardError(pushErr.Error()) {
return false, pushErr
}
// Auto-recover: pull --rebase then retry once
if pullErr := g.autoPullRebase(); pullErr != nil {
return false, pullErr
}
_, retryErr := g.run("git", append([]string{"push"}, args...)...)
if retryErr != nil {
return true, fmt.Errorf("push failed after auto-rebase: %w", retryErr)
}
return true, nil
}
// PushWithTags pushes commits and tag
func (g *Git) PushWithTags(tag string) (bool, error) {
branch, err := g.getCurrentBranch()
if err != nil {
return false, err
}
hasUpstream, err := g.HasUpstream()
if err != nil {
return false, err
}
var pulled bool
if !hasUpstream {
if err := g.setUpstream(branch); err != nil {
return false, err
}
// setUpstream already does a push, but we might still need to push the tag
} else {
// Normal push
p, err := g.pushWithAutoRebase()
if err != nil {
return false, fmt.Errorf("git push failed: %w", err)
}
pulled = p
}
if err := g.pushTag(tag); err != nil {
return pulled, err
}
return pulled, nil
}
// GetConfigUserName gets the git user.name
func (g *Git) GetConfigUserName() (string, error) {
name, err := g.runSilent("git", "config", "user.name")
if err != nil {
return "", err
}
return strings.TrimSpace(name), nil
}
// GetConfigUserEmail gets the git user.email
func (g *Git) GetConfigUserEmail() (string, error) {
email, err := g.runSilent("git", "config", "user.email")
if err != nil {
return "", err
}
return strings.TrimSpace(email), nil
}
// IsAheadOfRemote checks if local branch is ahead of remote
func (g *Git) IsAheadOfRemote() (bool, error) {
// Get current branch
branch, err := g.runSilent("git", "rev-parse", "--abbrev-ref", "HEAD")
if err != nil {
return false, err
}
// Check if ahead of origin
out, err := g.runSilent("git", "rev-list", "--count", fmt.Sprintf("origin/%s..HEAD", branch))
if err != nil {
// If origin/<branch> doesn't exist, we're not ahead
return false, nil
}
count := strings.TrimSpace(out)
if count == "0" || count == "" {
return false, nil
}
return true, nil
}
// HasPendingChanges returns true if there are uncommitted or unpushed changes.
// Used by CodeJob to ensure the file is visible to Jules before dispatching.
// It ignores changes to .env and .gitignore files.
func (g *Git) HasPendingChanges() (bool, error) {
// Uncommitted changes (staged or unstaged)
out, err := g.runSilent("git", "status", "--porcelain")
if err != nil {
return false, err
}
lines := strings.Split(strings.TrimSpace(out), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Ignore .env and .gitignore changes
if strings.HasSuffix(line, ".env") || strings.HasSuffix(line, ".gitignore") {
continue
}
// Found a change that is not ignored
return true, nil
}
// Unpushed commits
return g.IsAheadOfRemote()
}
// PushWithoutTags pushes commits without pushing tags
func (g *Git) PushWithoutTags() (bool, error) {
return g.pushWithAutoRebase()
}
// SetUserConfig sets git user name and email
func (g *Git) SetUserConfig(name, email string) error {
if _, err := g.run("git", "config", "user.name", name); err != nil {
return err
}
if _, err := g.run("git", "config", "user.email", email); err != nil {
return err
}
return nil
}
// InitRepo initializes a new git repository
func (g *Git) InitRepo(dir string) error {
if _, err := RunCommand("git", "init", dir); err != nil {
return err
}
if _, err := RunCommandInDir(dir, "git", "branch", "-M", "main"); err != nil {
// On fresh init with no commits, this might fail, but git init usually sets up a default branch.
// Newer git versions use init.defaultBranch.
// If it fails, it might mean there are no commits yet so HEAD doesn't point anywhere meaningful.
// We can ignore or handle.
// Actually "git branch -M main" works even with no commits in recent git.
// Let's assume it works or is not critical if we are on a version that defaults to master.
return err
}
return nil
}