summaryrefslogtreecommitdiff
path: root/internal/sync/branch_analyzer.go
blob: eaa6cdc1eb5ef45d2607d8b83db2aadb4f03f5d8 (plain)
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
package sync

import (
	_ "embed"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"text/template"
	"time"
)

//go:embed delete_script.tmpl
var deleteScriptTemplateText string

var deleteScriptTemplate = template.Must(template.New("deleteScript").Parse(deleteScriptTemplateText))

type deleteScriptTemplateData struct {
	GeneratedAt     string
	TotalAbandoned  int
	TotalIgnored    int
	TotalBranches   int
	RepositoryCount int
	ScriptBaseName  string
}

// BranchInfo holds information about a branch
type BranchInfo struct {
	Name              string
	LastCommit        time.Time
	Remote            string
	IsAbandoned       bool
	AbandonReason     string
	RemotesWithBranch []string // List of remotes that have this branch
}

// AbandonedBranchReport holds the analysis results
type AbandonedBranchReport struct {
	MainBranchUpdated        bool
	MainBranchLastCommit     time.Time
	AbandonedBranches        []BranchInfo
	AbandonedIgnoredBranches []BranchInfo // Abandoned branches that match exclusion patterns
	TotalBranches            int
	TotalIgnoredBranches     int
}

var defaultAutoDeleteProtectedBranches = map[string]map[string]struct{}{
	"xerl": {
		"hosts": {},
	},
}

func isProtectedFromAutoDelete(repoName, branchName string) bool {
	branches, ok := defaultAutoDeleteProtectedBranches[repoName]
	if !ok {
		return false
	}

	_, ok = branches[branchName]
	return ok
}

func filterProtectedBranchInfos(repoName string, branches []BranchInfo) []BranchInfo {
	if len(branches) == 0 {
		return branches
	}

	filtered := make([]BranchInfo, 0, len(branches))
	for _, branch := range branches {
		if isProtectedFromAutoDelete(repoName, branch.Name) {
			continue
		}
		filtered = append(filtered, branch)
	}

	return filtered
}

func filterProtectedAbandonedBranchReport(repoName string, report *AbandonedBranchReport) *AbandonedBranchReport {
	if report == nil {
		return nil
	}

	filtered := *report
	filtered.AbandonedBranches = filterProtectedBranchInfos(repoName, report.AbandonedBranches)
	filtered.AbandonedIgnoredBranches = filterProtectedBranchInfos(repoName, report.AbandonedIgnoredBranches)

	return &filtered
}

// analyzeAbandonedBranches analyzes branches to find abandoned ones
func (s *Syncer) analyzeAbandonedBranches() (*AbandonedBranchReport, error) {
	report := &AbandonedBranchReport{
		AbandonedBranches:        []BranchInfo{},
		AbandonedIgnoredBranches: []BranchInfo{},
	}

	// Get all branches
	allBranches, err := s.getAllBranches()
	if err != nil {
		return nil, fmt.Errorf("failed to get branches: %w", err)
	}

	// Filter branches based on exclusion patterns
	branches := s.branchFilter.FilterBranches(allBranches)
	report.TotalBranches = len(branches)

	// Get excluded branches for separate analysis
	excludedBranches := s.branchFilter.GetExcludedBranches(allBranches)
	report.TotalIgnoredBranches = len(excludedBranches)

	// Check main/master branch status
	mainBranch := s.findMainBranch(branches)
	if mainBranch != "" {
		mainInfo, err := s.getBranchInfo(mainBranch)
		if err == nil {
			// Consider project active if main branch has commits within last 3 years
			report.MainBranchUpdated = mainInfo.LastCommit.After(time.Now().AddDate(-3, 0, 0))
			report.MainBranchLastCommit = mainInfo.LastCommit
		}
	}

	// Only analyze if main branch is active (has commits within last 3 years)
	if !report.MainBranchUpdated {
		return report, nil
	}

	// Analyze each branch
	sixMonthsAgo := time.Now().AddDate(0, -6, 0)

	for _, branch := range branches {
		// Skip main/master branches
		if branch == "main" || branch == "master" {
			continue
		}

		branchInfo, err := s.getBranchInfo(branch)
		if err != nil {
			continue
		}

		// Check if branch is abandoned (no commits for 6+ months)
		if branchInfo.LastCommit.Before(sixMonthsAgo) {
			branchInfo.IsAbandoned = true
			daysSinceCommit := int(time.Since(branchInfo.LastCommit).Hours() / 24)
			branchInfo.AbandonReason = fmt.Sprintf("No commits for %d days", daysSinceCommit)
			report.AbandonedBranches = append(report.AbandonedBranches, *branchInfo)
		}
	}

	// Also analyze ignored branches for abandonment
	for _, branch := range excludedBranches {
		// Skip main/master branches even if they match exclusion patterns
		if branch == "main" || branch == "master" {
			continue
		}

		branchInfo, err := s.getBranchInfo(branch)
		if err != nil {
			continue
		}

		// Check if branch is abandoned (no commits for 6+ months)
		if branchInfo.LastCommit.Before(sixMonthsAgo) {
			branchInfo.IsAbandoned = true
			daysSinceCommit := int(time.Since(branchInfo.LastCommit).Hours() / 24)
			branchInfo.AbandonReason = fmt.Sprintf("No commits for %d days (ignored branch)", daysSinceCommit)
			report.AbandonedIgnoredBranches = append(report.AbandonedIgnoredBranches, *branchInfo)
		}
	}

	return filterProtectedAbandonedBranchReport(s.repoName, report), nil
}

// findMainBranch finds the main or master branch
func (s *Syncer) findMainBranch(branches []string) string {
	for _, branch := range branches {
		if branch == "main" || branch == "master" {
			return branch
		}
	}
	return ""
}

// getBranchInfo gets information about a specific branch
func (s *Syncer) getBranchInfo(branch string) (*BranchInfo, error) {
	info := &BranchInfo{
		Name:              branch,
		RemotesWithBranch: []string{},
	}

	// Find which remote has this branch and get the latest commit
	var latestCommit time.Time
	var latestRemote string

	for i := range s.config.Organizations {
		org := &s.config.Organizations[i]

		// Skip backup locations if backup is not enabled
		if org.BackupLocation && !s.backupEnabled {
			continue
		}

		remoteName := s.getRemoteName(org)

		if s.remoteBranchExists(remoteName, branch) {
			// Add this remote to the list
			info.RemotesWithBranch = append(info.RemotesWithBranch, remoteName)

			// Get last commit date for this branch on this remote
			commitTime, err := s.getLastCommitTime(remoteName, branch)
			if err == nil && (latestCommit.IsZero() || commitTime.After(latestCommit)) {
				latestCommit = commitTime
				latestRemote = remoteName
			}
		}
	}

	if latestCommit.IsZero() {
		// If no remote has the branch, check local
		commitTime, err := s.getLastCommitTime("", branch)
		if err != nil {
			return nil, fmt.Errorf("failed to get commit time for branch %s: %w", branch, err)
		}
		latestCommit = commitTime
		latestRemote = "local"
	}

	info.LastCommit = latestCommit
	info.Remote = latestRemote
	return info, nil
}

// getLastCommitTime gets the last commit time for a branch
func (s *Syncer) getLastCommitTime(remoteName, branch string) (time.Time, error) {
	var ref string
	if remoteName != "" {
		ref = fmt.Sprintf("%s/%s", remoteName, branch)
	} else {
		ref = branch
	}

	// Get Unix timestamp of last commit
	cmd := gitCommand(s.repoPath(), "log", "-1", "--format=%ct", ref)
	output, err := cmd.Output()
	if err != nil {
		return time.Time{}, err
	}

	timestampStr := strings.TrimSpace(string(output))
	timestamp, err := strconv.ParseInt(timestampStr, 10, 64)
	if err != nil {
		return time.Time{}, fmt.Errorf("failed to parse timestamp: %w", err)
	}

	return time.Unix(timestamp, 0), nil
}

// formatAbandonedBranchReport formats the report for display
func formatAbandonedBranchReport(report *AbandonedBranchReport, repoName string) string {
	report = filterProtectedAbandonedBranchReport(repoName, report)
	if !report.MainBranchUpdated {
		return "" // Don't report on inactive repos
	}

	if len(report.AbandonedBranches) == 0 && len(report.AbandonedIgnoredBranches) == 0 {
		return "" // No abandoned branches
	}

	var sb strings.Builder
	sb.WriteString(fmt.Sprintf("\nšŸ” Abandoned branches in %s:\n", repoName))
	sb.WriteString(fmt.Sprintf("   Main branch last updated: %s\n", report.MainBranchLastCommit.Format("2006-01-02")))

	if len(report.AbandonedBranches) > 0 {
		sb.WriteString(fmt.Sprintf("   Found %d abandoned branches (no commits for 6+ months):\n\n", len(report.AbandonedBranches)))
		for _, branch := range report.AbandonedBranches {
			sb.WriteString(fmt.Sprintf("   - %s (last commit: %s, %s)\n",
				branch.Name,
				branch.LastCommit.Format("2006-01-02"),
				branch.AbandonReason))
		}
	}

	if len(report.AbandonedIgnoredBranches) > 0 {
		sb.WriteString(fmt.Sprintf("\n   Found %d abandoned IGNORED branches (no commits for 6+ months):\n\n", len(report.AbandonedIgnoredBranches)))
		for _, branch := range report.AbandonedIgnoredBranches {
			sb.WriteString(fmt.Sprintf("   - %s (last commit: %s, %s)\n",
				branch.Name,
				branch.LastCommit.Format("2006-01-02"),
				branch.AbandonReason))
		}
	}

	return sb.String()
}

// GenerateAbandonedBranchSummary generates a summary of all abandoned branches across repos
func (s *Syncer) GenerateAbandonedBranchSummary() string {
	if len(s.abandonedReports) == 0 {
		return ""
	}

	totalAbandoned := 0
	totalAbandonedIgnored := 0
	reposWithAbandoned := 0

	for repoName, report := range s.abandonedReports {
		report = filterProtectedAbandonedBranchReport(repoName, report)
		if len(report.AbandonedBranches) > 0 || len(report.AbandonedIgnoredBranches) > 0 {
			totalAbandoned += len(report.AbandonedBranches)
			totalAbandonedIgnored += len(report.AbandonedIgnoredBranches)
			reposWithAbandoned++
		}
	}

	if totalAbandoned == 0 && totalAbandonedIgnored == 0 {
		return ""
	}

	var sb strings.Builder
	sb.WriteString("\n")
	sb.WriteString(strings.Repeat("=", 70))
	sb.WriteString("\nšŸ“Š ABANDONED BRANCHES SUMMARY\n")
	sb.WriteString(strings.Repeat("=", 70))
	sb.WriteString("\n\n")
	sb.WriteString(fmt.Sprintf("Found %d abandoned branches", totalAbandoned))
	if totalAbandonedIgnored > 0 {
		sb.WriteString(fmt.Sprintf(" + %d ignored branches", totalAbandonedIgnored))
	}
	sb.WriteString(fmt.Sprintf(" across %d repositories\n\n", reposWithAbandoned))

	// Group by repository
	for repoName, report := range s.abandonedReports {
		report = filterProtectedAbandonedBranchReport(repoName, report)
		if len(report.AbandonedBranches) == 0 && len(report.AbandonedIgnoredBranches) == 0 {
			continue
		}

		totalBranches := len(report.AbandonedBranches) + len(report.AbandonedIgnoredBranches)
		sb.WriteString(fmt.Sprintf("šŸ“ %s (%d branches):\n", repoName, totalBranches))

		// Regular abandoned branches
		if len(report.AbandonedBranches) > 0 {
			sb.WriteString("   Regular branches:\n")
			for _, branch := range report.AbandonedBranches {
				sb.WriteString(fmt.Sprintf("   - %s (last commit: %s)\n",
					branch.Name,
					branch.LastCommit.Format("2006-01-02")))
			}
		}

		// Ignored abandoned branches
		if len(report.AbandonedIgnoredBranches) > 0 {
			sb.WriteString("   Ignored branches:\n")
			for _, branch := range report.AbandonedIgnoredBranches {
				sb.WriteString(fmt.Sprintf("   - %s (last commit: %s)\n",
					branch.Name,
					branch.LastCommit.Format("2006-01-02")))
			}
		}

		sb.WriteString("\n")
	}

	sb.WriteString("šŸ’” Tip: Consider deleting these branches if they're no longer needed:\n")
	sb.WriteString("   git push origin --delete <branch-name>\n")
	sb.WriteString(strings.Repeat("=", 70))
	sb.WriteString("\n")

	return sb.String()
}

// GenerateDeleteCommands generates shell commands to delete abandoned branches
func (s *Syncer) GenerateDeleteCommands(report *AbandonedBranchReport, repoName string) string {
	report = filterProtectedAbandonedBranchReport(repoName, report)
	if len(report.AbandonedBranches) == 0 && len(report.AbandonedIgnoredBranches) == 0 {
		return ""
	}

	var sb strings.Builder
	sb.WriteString(fmt.Sprintf("\n# Delete commands for abandoned branches in %s\n", repoName))
	sb.WriteString("# Review these commands carefully before running them!\n\n")

	// Process regular abandoned branches
	if len(report.AbandonedBranches) > 0 {
		sb.WriteString("# === REGULAR BRANCHES ===\n")
		for _, branch := range report.AbandonedBranches {
			sb.WriteString(fmt.Sprintf("# Branch: %s (last commit: %s)\n", branch.Name, branch.LastCommit.Format("2006-01-02")))

			// Delete from all remotes that have this branch
			if len(branch.RemotesWithBranch) > 0 {
				sb.WriteString("# Delete from remotes:\n")
				for _, remote := range branch.RemotesWithBranch {
					sb.WriteString(fmt.Sprintf("git push %s --delete %s\n", remote, branch.Name))
				}
			}

			// Delete local branch
			sb.WriteString("# Delete local branch:\n")
			sb.WriteString(fmt.Sprintf("git branch -D %s\n\n", branch.Name))
		}
	}

	// Process ignored abandoned branches
	if len(report.AbandonedIgnoredBranches) > 0 {
		sb.WriteString("# === IGNORED BRANCHES ===\n")
		for _, branch := range report.AbandonedIgnoredBranches {
			sb.WriteString(fmt.Sprintf("# Branch: %s (last commit: %s) [IGNORED]\n", branch.Name, branch.LastCommit.Format("2006-01-02")))

			// Delete from all remotes that have this branch
			if len(branch.RemotesWithBranch) > 0 {
				sb.WriteString("# Delete from remotes:\n")
				for _, remote := range branch.RemotesWithBranch {
					sb.WriteString(fmt.Sprintf("git push %s --delete %s\n", remote, branch.Name))
				}
			}

			// Delete local branch
			sb.WriteString("# Delete local branch:\n")
			sb.WriteString(fmt.Sprintf("git branch -D %s\n\n", branch.Name))
		}
	}

	return sb.String()
}

func writeDeleteScriptTemplate(writer io.Writer, templateName string, data deleteScriptTemplateData) error {
	if err := deleteScriptTemplate.ExecuteTemplate(writer, templateName, data); err != nil {
		return fmt.Errorf("failed to execute %s template: %w", templateName, err)
	}

	return nil
}

func writeBranchDeletionBlock(writer io.Writer, branches []BranchInfo, reviewBranchType, deleteMessagePrefix string) error {
	for _, branch := range branches {
		if _, err := fmt.Fprintf(writer, "if [[ \"$MODE\" == \"review\" || \"$MODE\" == \"review-full\" ]]; then\n"); err != nil {
			return fmt.Errorf("failed to write review mode condition for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    if [[ -n \"$main_branch\" ]]; then\n"); err != nil {
			return fmt.Errorf("failed to write main branch check for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "        review_branch \"%s\" \"$main_branch\" \"%s\" \"%s\"\n", branch.Name, branch.LastCommit.Format("2006-01-02"), reviewBranchType); err != nil {
			return fmt.Errorf("failed to write review command for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    fi\n"); err != nil {
			return fmt.Errorf("failed to write review branch end for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "else\n"); err != nil {
			return fmt.Errorf("failed to write delete branch condition for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    echo \"  %s%s (last commit: %s)\"\n", deleteMessagePrefix, branch.Name, branch.LastCommit.Format("2006-01-02")); err != nil {
			return fmt.Errorf("failed to write delete message for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    # Check if we're on the branch to be deleted\n"); err != nil {
			return fmt.Errorf("failed to write current branch comment for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    current_branch=$(git branch --show-current)\n"); err != nil {
			return fmt.Errorf("failed to write current branch command for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    if [[ \"$current_branch\" == \"%s\" ]]; then\n", branch.Name); err != nil {
			return fmt.Errorf("failed to write current branch condition for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "        echo \"    Switching from %s to main/master branch before deletion...\"\n", branch.Name); err != nil {
			return fmt.Errorf("failed to write branch switch message for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "        main_branch=$(find_main_branch)\n"); err != nil {
			return fmt.Errorf("failed to write find main branch command for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "        if [[ -n \"$main_branch\" ]]; then\n"); err != nil {
			return fmt.Errorf("failed to write branch switch check for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "            execute_cmd git checkout \"$main_branch\"\n"); err != nil {
			return fmt.Errorf("failed to write checkout command for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "        else\n"); err != nil {
			return fmt.Errorf("failed to write missing main branch else block for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "            echo \"    āš ļø  No main/master branch found to switch to!\"\n"); err != nil {
			return fmt.Errorf("failed to write missing main branch message for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "            echo \"    Skipping deletion of %s\"\n", branch.Name); err != nil {
			return fmt.Errorf("failed to write skip branch message for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "        fi\n"); err != nil {
			return fmt.Errorf("failed to write main branch switch end for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    fi\n"); err != nil {
			return fmt.Errorf("failed to write current branch condition end for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    # Skip to next branch if we couldn't switch\n"); err != nil {
			return fmt.Errorf("failed to write skip comment for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    if [[ \"$current_branch\" == \"%s\" ]] && [[ -z \"$main_branch\" ]]; then\n", branch.Name); err != nil {
			return fmt.Errorf("failed to write skip condition for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "        continue\n"); err != nil {
			return fmt.Errorf("failed to write continue for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "    fi\n"); err != nil {
			return fmt.Errorf("failed to write skip condition end for branch %s: %w", branch.Name, err)
		}
		for _, remote := range branch.RemotesWithBranch {
			if _, err := fmt.Fprintf(writer, "    execute_cmd git push %s --delete \"%s\"\n", remote, branch.Name); err != nil {
				return fmt.Errorf("failed to write remote delete command for branch %s: %w", branch.Name, err)
			}
		}
		if _, err := fmt.Fprintf(writer, "    execute_cmd git branch -D \"%s\"\n", branch.Name); err != nil {
			return fmt.Errorf("failed to write local delete command for branch %s: %w", branch.Name, err)
		}
		if _, err := fmt.Fprintf(writer, "fi\n\n"); err != nil {
			return fmt.Errorf("failed to write branch block end for branch %s: %w", branch.Name, err)
		}
	}

	return nil
}

// GenerateDeleteScript generates a shell script file to delete all abandoned branches
func (s *Syncer) GenerateDeleteScript() (string, error) {
	if len(s.abandonedReports) == 0 {
		return "", nil
	}

	// Count total abandoned branches
	totalAbandoned := 0
	totalIgnored := 0
	for repoName, report := range s.abandonedReports {
		report = filterProtectedAbandonedBranchReport(repoName, report)
		totalAbandoned += len(report.AbandonedBranches)
		totalIgnored += len(report.AbandonedIgnoredBranches)
	}

	if totalAbandoned == 0 && totalIgnored == 0 {
		return "", nil
	}

	// Generate script filename with timestamp
	timestamp := time.Now().Format("20060102_150405")
	scriptPath := filepath.Join(s.workDir, fmt.Sprintf("delete_abandoned_branches_%s.sh", timestamp))
	scriptBaseName := filepath.Base(scriptPath)

	// Create the script file
	file, err := os.Create(scriptPath)
	if err != nil {
		return "", fmt.Errorf("failed to create script file: %w", err)
	}
	defer file.Close()

	if err := writeDeleteScriptTemplate(file, "deleteScriptPreamble", deleteScriptTemplateData{
		GeneratedAt:     time.Now().Format("2006-01-02 15:04:05"),
		TotalAbandoned:  totalAbandoned,
		TotalIgnored:    totalIgnored,
		TotalBranches:   totalAbandoned + totalIgnored,
		RepositoryCount: len(s.abandonedReports),
		ScriptBaseName:  scriptBaseName,
	}); err != nil {
		return scriptPath, err
	}

	// Process each repository
	for repoName, report := range s.abandonedReports {
		report = filterProtectedAbandonedBranchReport(repoName, report)
		if len(report.AbandonedBranches) == 0 && len(report.AbandonedIgnoredBranches) == 0 {
			continue
		}

		fmt.Fprintf(file, "# ======================================\n")
		fmt.Fprintf(file, "# Repository: %s\n", repoName)
		fmt.Fprintf(file, "# ======================================\n")
		fmt.Fprintf(file, "echo\n")
		fmt.Fprintf(file, "echo \"šŸ“ Processing repository: %s\"\n", repoName)
		fmt.Fprintf(file, "cd \"%s/%s\" || { echo \"Failed to change to repository directory\"; exit 1; }\n\n", s.workDir, repoName)

		// Find main branch for review mode
		fmt.Fprintf(file, "if [[ \"$MODE\" == \"review\" || \"$MODE\" == \"review-full\" ]]; then\n")
		fmt.Fprintf(file, "    main_branch=$(find_main_branch)\n")
		fmt.Fprintf(file, "    if [[ -z \"$main_branch\" ]]; then\n")
		fmt.Fprintf(file, "        echo -e \"${RED}āš ļø  No main/master branch found in %s${NC}\"\n", repoName)
		fmt.Fprintf(file, "    fi\n")
		fmt.Fprintf(file, "fi\n\n")

		// Process regular abandoned branches
		if len(report.AbandonedBranches) > 0 {
			fmt.Fprintf(file, "# Regular abandoned branches\n")
			if err := writeBranchDeletionBlock(file, report.AbandonedBranches, "regular", "šŸ”ø Deleting branch: "); err != nil {
				return scriptPath, err
			}
		}

		// Process ignored abandoned branches
		if len(report.AbandonedIgnoredBranches) > 0 {
			fmt.Fprintf(file, "# Ignored abandoned branches\n")
			if err := writeBranchDeletionBlock(file, report.AbandonedIgnoredBranches, "ignored", "šŸ”¹ Deleting ignored branch: "); err != nil {
				return scriptPath, err
			}
		}
	}

	if err := writeDeleteScriptTemplate(file, "deleteScriptFooter", deleteScriptTemplateData{
		ScriptBaseName: scriptBaseName,
	}); err != nil {
		return scriptPath, err
	}

	// Make the script executable
	if err := os.Chmod(scriptPath, 0755); err != nil {
		return scriptPath, fmt.Errorf("failed to make script executable: %w", err)
	}

	return scriptPath, nil
}