-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
498 lines (410 loc) · 14.2 KB
/
main.go
File metadata and controls
498 lines (410 loc) · 14.2 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
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
)
// Styles for consistent UI
var (
titleStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#7D56F4")).
MarginLeft(2)
errorStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#F25D94")).
Bold(true)
successStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#04B575")).
Bold(true)
warningStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FFB347")).
Bold(true)
infoStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#7D56F4"))
subtleStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#6C7086"))
)
type ChangedLine struct {
LineNumber int
Content string
}
type CommitInfo struct {
Hash string
Subject string
Lines []int
HasConflictRisk bool
ConflictReason string
}
type FixupWarning struct {
Count int
}
func main() {
if len(os.Args) < 2 {
fmt.Println(errorStyle.Render("Usage: " + os.Args[0] + " <filename>"))
os.Exit(1)
}
filename := os.Args[1]
if _, failure := os.Stat(filename); os.IsNotExist(failure) {
fmt.Println(errorStyle.Render("Error: " + filename + " does not exist"))
os.Exit(1)
}
fmt.Println(titleStyle.Render("🛠️ Git Handyman 🧰"))
fmt.Println(subtleStyle.Render("Let someone else handle your fixup chores\n"))
// Check for existing fixup commits
if err := checkExistingFixups(); err != nil {
fmt.Println(errorStyle.Render("Error checking for existing fixups: " + err.Error()))
os.Exit(1)
}
fmt.Println(infoStyle.Render("🔍 Analyzing changes in " + filename + "..."))
// Check if there are changes
if !hasChanges(filename) {
fmt.Println(warningStyle.Render("No changes found in " + filename))
os.Exit(0)
}
// Get changed lines from diff
changedLines, failure := getChangedLines(filename)
if failure != nil {
fmt.Println(errorStyle.Render("Error getting changed lines: " + failure.Error()))
os.Exit(1)
}
if len(changedLines) == 0 {
fmt.Println(warningStyle.Render("No changed lines found"))
os.Exit(0)
}
fmt.Println(subtleStyle.Render("Changed lines: " + formatLines(changedLines)))
// Get commit info for each line with conflict analysis
commits, failure := getCommitsForLines(filename, changedLines)
if failure != nil {
fmt.Println(errorStyle.Render("Error getting commit info: " + failure.Error()))
os.Exit(1)
}
if len(commits) == 0 {
fmt.Println(warningStyle.Render("No commits found for changed lines"))
os.Exit(0)
}
fmt.Printf("\n%s\n", infoStyle.Render(fmt.Sprintf("📋 Found changes affecting %d commit(s):", len(commits))))
hasConflicts := false
for _, commit := range commits {
conflictIndicator := ""
if commit.HasConflictRisk {
conflictIndicator = warningStyle.Render(" ⚠️ ") + subtleStyle.Render("("+commit.ConflictReason+")")
hasConflicts = true
}
fmt.Printf(" %s: %s %s%s\n",
warningStyle.Render(commit.Hash[:8]),
commit.Subject,
subtleStyle.Render("(lines "+formatLines(commit.Lines)+")"),
conflictIndicator)
}
if hasConflicts {
fmt.Printf("\n%s\n", warningStyle.Render("⚠️ Some fixup commits may have merge conflicts during rebase."))
var proceed bool
form := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title("Do you want to proceed anyway?").
Description("You can resolve conflicts during the interactive rebase.").
Value(&proceed),
),
).WithTheme(huh.ThemeCharm())
if err := form.Run(); err != nil {
fmt.Println(errorStyle.Render("Error: " + err.Error()))
os.Exit(1)
}
if !proceed {
fmt.Println(subtleStyle.Render("Operation cancelled by user."))
os.Exit(0)
}
}
// Process each commit
for i, commit := range commits {
fmt.Printf("\n%s\n",
infoStyle.Render(fmt.Sprintf("🔧 Creating fixup %d/%d for %s", i+1, len(commits), commit.Hash[:8])))
fmt.Println(subtleStyle.Render(" Staging lines: " + formatLines(commit.Lines)))
// Stage the specific lines for this commit using git add -p with automation
if failure := stageLines(filename, commit.Lines); failure != nil {
fmt.Println(errorStyle.Render(" ✗ Failed to stage lines: " + failure.Error()))
os.Exit(1)
}
// Create fixup commit
if failure := createFixupCommit(commit.Hash); failure != nil {
fmt.Println(errorStyle.Render(" ✗ Failed to create fixup commit: " + failure.Error()))
os.Exit(1)
}
fmt.Println(successStyle.Render(" ✓ Created fixup commit"))
}
fmt.Printf("\n%s\n", successStyle.Render("🎉 All fixup commits created!"))
// Show rebase command
if len(commits) > 0 {
parentCommit, failure := getParentCommit(commits[0].Hash)
if failure == nil && parentCommit != "" {
fmt.Printf("\n%s\n", infoStyle.Render("To apply them:"))
fmt.Println(warningStyle.Render("git rebase -i --autosquash " + parentCommit))
}
}
}
func checkExistingFixups() error {
// Get list of commits with fixup in the subject
command := exec.Command("git", "log", "--oneline", "--grep=^fixup!", "--grep=^squash!", "-E")
output, err := command.Output()
if err != nil {
// If git log fails, just continue (might be empty repo, etc.)
return nil
}
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
if len(lines) == 1 && lines[0] == "" {
// No fixup commits found
return nil
}
count := len(lines)
fmt.Printf("\n%s\n", warningStyle.Render("⚠️ Warning: Existing Fixup Commits Detected"))
fmt.Printf("%s\n", subtleStyle.Render(fmt.Sprintf("There are already %d fixup commits in this repo.", count)))
fmt.Printf("%s\n\n", subtleStyle.Render("These are likely to create merge conflicts that will make rebasing unnecessarily complicated."))
var proceed bool
form := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title("Would you like to stop and deal with those before creating new fixup commits?").
Description("Choose 'Yes' to abort and handle existing fixups first, or 'No' to proceed anyway.").
Value(&proceed),
),
).WithTheme(huh.ThemeCharm())
if err := form.Run(); err != nil {
return err
}
if proceed {
fmt.Println(subtleStyle.Render("Operation aborted. Please handle existing fixup commits first."))
fmt.Println(infoStyle.Render("Suggestion: Run 'git rebase -i --autosquash <base-commit>' to apply existing fixups."))
os.Exit(0)
}
fmt.Println(subtleStyle.Render("Proceeding with new fixup commits...\n"))
return nil
}
func hasChanges(filename string) bool {
command := exec.Command("git", "diff", "--name-only", filename)
output, failure := command.Output()
return failure == nil && strings.TrimSpace(string(output)) != ""
}
func getChangedLines(filename string) ([]int, error) {
command := exec.Command("git", "diff", filename)
output, failure := command.Output()
if failure != nil {
return nil, failure
}
var changedLines []int
scanner := bufio.NewScanner(strings.NewReader(string(output)))
hunkRegex := regexp.MustCompile(`^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@`)
var currentLine int
for scanner.Scan() {
line := scanner.Text()
if matches := hunkRegex.FindStringSubmatch(line); matches != nil {
currentLine, _ = strconv.Atoi(matches[1])
} else if strings.HasPrefix(line, "+") && !strings.HasPrefix(line, "+++") {
changedLines = append(changedLines, currentLine)
currentLine++
} else if strings.HasPrefix(line, " ") {
currentLine++
}
}
return changedLines, nil
}
func getCommitsForLines(filename string, lines []int) ([]CommitInfo, error) {
lineToCommit := make(map[int]string)
commitToSubject := make(map[string]string)
// Get commit hash for each line using git blame
for _, lineNum := range lines {
command := exec.Command("git", "blame", "-L", fmt.Sprintf("%d,%d", lineNum, lineNum), "HEAD", "--", filename)
output, failure := command.Output()
if failure != nil {
continue
}
line := strings.TrimSpace(string(output))
if line == "" {
continue
}
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
commitHash := parts[0]
if strings.HasPrefix(commitHash, "00000000") {
continue
}
// Strip ^ prefix if present (indicates initial commit)
if strings.HasPrefix(commitHash, "^") {
commitHash = commitHash[1:]
}
lineToCommit[lineNum] = commitHash
// Get commit subject if we haven't already
if _, exists := commitToSubject[commitHash]; !exists {
command := exec.Command("git", "log", "--format=%s", "-n", "1", commitHash)
output, failure := command.Output()
if failure == nil {
commitToSubject[commitHash] = strings.TrimSpace(string(output))
}
}
}
// Group lines by commit, preserving order of first appearance
var seenCommits []string
commitToLines := make(map[string][]int)
for _, lineNum := range lines {
if commitHash, exists := lineToCommit[lineNum]; exists {
if _, seen := commitToLines[commitHash]; !seen {
seenCommits = append(seenCommits, commitHash)
commitToLines[commitHash] = []int{}
}
commitToLines[commitHash] = append(commitToLines[commitHash], lineNum)
}
}
// Create result slice with conflict analysis
var commits []CommitInfo
for _, commitHash := range seenCommits {
commit := CommitInfo{
Hash: commitHash,
Subject: commitToSubject[commitHash],
Lines: commitToLines[commitHash],
}
// Analyze potential conflicts
hasConflict, reason := analyzeConflictRisk(filename, commitHash, commitToLines[commitHash])
commit.HasConflictRisk = hasConflict
commit.ConflictReason = reason
commits = append(commits, commit)
}
return commits, nil
}
func analyzeConflictRisk(filename string, commitHash string, lines []int) (bool, string) {
// Check if there have been changes to the same lines since this commit
for _, lineNum := range lines {
// Get the commit history for this specific line since the target commit
command := exec.Command("git", "log", "--format=%H", fmt.Sprintf("%s..HEAD", commitHash), "-L", fmt.Sprintf("%d,%d:%s", lineNum, lineNum, filename))
output, err := command.Output()
if err != nil {
continue
}
commits := strings.Fields(strings.TrimSpace(string(output)))
if len(commits) > 0 {
return true, "line modified since original commit"
}
}
// Check if the target commit is very recent (potential for context conflicts)
command := exec.Command("git", "rev-list", "--count", fmt.Sprintf("%s..HEAD", commitHash))
output, err := command.Output()
if err == nil {
count, err := strconv.Atoi(strings.TrimSpace(string(output)))
if err == nil && count > 20 {
return true, "commit is distant, context may have changed"
}
}
// Check if there are merge commits between target commit and HEAD
command = exec.Command("git", "rev-list", "--merges", fmt.Sprintf("%s..HEAD", commitHash))
output, err = command.Output()
if err == nil && strings.TrimSpace(string(output)) != "" {
return true, "merge commits present, potential context conflicts"
}
return false, ""
}
func stageLines(filename string, targetLines []int) error {
// Validate input
if len(targetLines) == 0 {
return fmt.Errorf("no target lines specified")
}
// Reset staging area first
command := exec.Command("git", "reset", "HEAD", filename)
command.Run()
// Get current file content and original content
currentContent, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read current file: %v", err)
}
// Get the original file content from HEAD
command = exec.Command("git", "show", "HEAD:"+filename)
originalContent, err := command.Output()
if err != nil {
return fmt.Errorf("failed to get original file content: %v", err)
}
// Check if there are any changes at all
if string(currentContent) == string(originalContent) {
return fmt.Errorf("no changes detected in file")
}
// Create target set for quick lookup
targetSet := make(map[int]bool)
for _, line := range targetLines {
targetSet[line] = true
}
// Parse current and original content into lines
currentLines := strings.Split(string(currentContent), "\n")
originalLines := strings.Split(string(originalContent), "\n")
// Create a version with only target line changes
var selectiveLines []string
// Start with the original content
for i, originalLine := range originalLines {
lineNum := i + 1
if lineNum <= len(currentLines) && targetSet[lineNum] {
// Use the modified line for target lines
selectiveLines = append(selectiveLines, currentLines[i])
} else {
// Use the original line for non-target lines
selectiveLines = append(selectiveLines, originalLine)
}
}
// Handle any additional lines beyond the original file length
if len(currentLines) > len(originalLines) {
for i := len(originalLines); i < len(currentLines); i++ {
lineNum := i + 1
if targetSet[lineNum] {
selectiveLines = append(selectiveLines, currentLines[i])
}
}
}
// Write the selective version to a temporary file
tmpFile := filename + ".tmp-staging"
selectiveContent := strings.Join(selectiveLines, "\n")
if err := os.WriteFile(tmpFile, []byte(selectiveContent), 0644); err != nil {
return fmt.Errorf("failed to write temporary file: %v", err)
}
defer os.Remove(tmpFile)
// Replace working file with selective version, stage it, then restore working file
if err := os.Rename(tmpFile, filename); err != nil {
return fmt.Errorf("failed to replace file with selective version: %v", err)
}
// Stage the selective version
command = exec.Command("git", "add", filename)
if err := command.Run(); err != nil {
// Restore the original working file
os.WriteFile(filename, currentContent, 0644)
return fmt.Errorf("failed to stage selective changes: %v", err)
}
// Restore the original working file
if err := os.WriteFile(filename, currentContent, 0644); err != nil {
return fmt.Errorf("failed to restore working file: %v", err)
}
return nil
}
func createFixupCommit(commitHash string) error {
command := exec.Command("git", "commit", "--fixup="+commitHash)
return command.Run()
}
func getParentCommit(commitHash string) (string, error) {
command := exec.Command("git", "rev-parse", commitHash+"^")
output, failure := command.Output()
if failure != nil {
return "", failure
}
return strings.TrimSpace(string(output)), nil
}
func formatLines(lines []int) string {
if len(lines) == 0 {
return ""
}
strLines := make([]string, len(lines))
for i, line := range lines {
strLines[i] = strconv.Itoa(line)
}
return strings.Join(strLines, ", ")
}