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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
|
package cli
import (
"fmt"
"math/rand"
"strings"
"codeberg.org/snonux/gitsyncer/internal/codeberg"
"codeberg.org/snonux/gitsyncer/internal/config"
"codeberg.org/snonux/gitsyncer/internal/github"
"codeberg.org/snonux/gitsyncer/internal/state"
"codeberg.org/snonux/gitsyncer/internal/sync"
)
// HandleSync handles syncing a single repository
func HandleSync(cfg *config.Config, flags *Flags) int {
stateManager, syncState, err := loadSyncState(flags.WorkDir)
if err != nil {
fmt.Printf("Warning: Failed to load sync state: %v\n", err)
}
decision := evaluateSyncPolicy(flags.SyncRepo, syncState, flags.DryRun, flags.Force, flags.Throttle)
if decision.Message != "" {
fmt.Println(decision.Message)
}
if decision.SetNextAllowed && stateManager != nil && !flags.DryRun {
syncState.SetNextRepoSyncAllowed(flags.SyncRepo, decision.NextAllowed)
if err := stateManager.Save(syncState); err != nil {
fmt.Printf("Warning: Failed to save sync state: %v\n", err)
}
}
if decision.Skip {
return 0
}
// If create-github-repos is enabled, create the repo if needed
if flags.CreateGitHubRepos {
if err := createGitHubRepoIfNeeded(cfg, flags.SyncRepo); err != nil {
fmt.Printf("ERROR: %v\n", err)
return 1
}
}
// If create-codeberg-repos is enabled, create the repo if needed
if flags.CreateCodebergRepos {
if err := createCodebergRepoIfNeeded(cfg, flags.SyncRepo); err != nil {
fmt.Printf("ERROR: %v\n", err)
return 1
}
}
syncer := sync.New(cfg, flags.WorkDir)
syncer.SetBackupEnabled(flags.Backup)
if err := syncer.SyncRepository(flags.SyncRepo); err != nil {
fmt.Printf("ERROR: Sync failed: %v\n", err)
return 1
}
if stateManager != nil {
recordRepoSync(flags.SyncRepo, syncState, flags.Throttle)
if err := stateManager.Save(syncState); err != nil {
fmt.Printf("Warning: Failed to save sync state: %v\n", err)
}
}
// Also sync descriptions for this single repository
descCache := loadDescriptionCache(flags.WorkDir)
syncRepoDescriptions(cfg, flags.DryRun, flags.SyncRepo, "", "", descCache)
if err := saveDescriptionCache(flags.WorkDir, descCache); err != nil {
fmt.Printf("Warning: Failed to save descriptions cache: %v\n", err)
}
return 0
}
// HandleSyncAll handles syncing all configured repositories
func HandleSyncAll(cfg *config.Config, flags *Flags) int {
if len(cfg.Repositories) == 0 {
fmt.Println("No repositories configured. Add repositories to the config file.")
return 1
}
repoNames := shuffledRepoNames(cfg.Repositories)
stateManager, syncState, err := loadSyncState(flags.WorkDir)
if err != nil {
fmt.Printf("Warning: Failed to load sync state: %v\n", err)
}
// Initialize GitHub client if needed
var githubClient github.Client
var hasGithubClient bool
if flags.CreateGitHubRepos {
if client := initGitHubClient(cfg); client != nil {
githubClient = *client
hasGithubClient = true
}
}
// Initialize Codeberg client if needed
var codebergClient codeberg.Client
var hasCodebergClient bool
if flags.CreateCodebergRepos {
if client := initCodebergClient(cfg); client != nil {
codebergClient = *client
hasCodebergClient = true
}
}
syncer := sync.New(cfg, flags.WorkDir)
syncer.SetBackupEnabled(flags.Backup)
successCount := 0
// Load descriptions cache
descCache := loadDescriptionCache(flags.WorkDir)
for i, repo := range repoNames {
fmt.Printf("\n[%d/%d] Syncing %s...\n", i+1, len(repoNames), repo)
decision := evaluateSyncPolicy(repo, syncState, flags.DryRun, flags.Force, flags.Throttle)
if decision.Message != "" {
fmt.Println(decision.Message)
}
if decision.SetNextAllowed && stateManager != nil && !flags.DryRun {
syncState.SetNextRepoSyncAllowed(repo, decision.NextAllowed)
if err := stateManager.Save(syncState); err != nil {
fmt.Printf("Warning: Failed to save sync state: %v\n", err)
}
}
if decision.Skip {
continue
}
// Create GitHub repo if needed
if hasGithubClient {
if err := createRepoWithClient(&githubClient, repo, fmt.Sprintf("Mirror of %s", repo)); err != nil {
fmt.Printf("ERROR: Failed to create GitHub repo %s: %v\n", repo, err)
fmt.Printf("Stopping sync due to error.\n")
return 1
}
}
// Create Codeberg repo if needed
if hasCodebergClient {
fmt.Printf("Checking/creating Codeberg repository %s...\n", repo)
if err := codebergClient.CreateRepo(repo, fmt.Sprintf("Mirror of %s", repo), false); err != nil {
fmt.Printf("Warning: Failed to create Codeberg repo %s: %v\n", repo, err)
}
}
if err := syncer.SyncRepository(repo); err != nil {
fmt.Printf("ERROR: Failed to sync %s: %v\n", repo, err)
fmt.Printf("Stopping sync due to error.\n")
return 1
}
if stateManager != nil {
recordRepoSync(repo, syncState, flags.Throttle)
if err := stateManager.Save(syncState); err != nil {
fmt.Printf("Warning: Failed to save sync state: %v\n", err)
}
}
successCount++
// Sync descriptions after repo sync
syncRepoDescriptions(cfg, flags.DryRun, repo, "", "", descCache)
}
// Save descriptions cache
if err := saveDescriptionCache(flags.WorkDir, descCache); err != nil {
fmt.Printf("Warning: Failed to save descriptions cache: %v\n", err)
}
fmt.Printf("\nSuccessfully synced all %d repositories!\n", successCount)
// Print abandoned branches summary
if summary := syncer.GenerateAbandonedBranchSummary(); summary != "" {
fmt.Print(summary)
}
printDeleteScript(syncer)
return 0
}
// HandleSyncCodebergPublic handles syncing all public Codeberg repositories
func HandleSyncCodebergPublic(cfg *config.Config, flags *Flags) int {
codebergOrg := cfg.FindCodebergOrg()
if codebergOrg == nil {
fmt.Println("No Codeberg organization found in configuration")
return 1
}
fmt.Printf("Fetching public repositories from Codeberg user/org: %s...\n", codebergOrg.Name)
client := codeberg.NewClient(codebergOrg.Name, codebergOrg.CodebergToken)
// Try fetching as organization first, then as user
repos, err := client.ListPublicRepos()
if err != nil {
fmt.Println("Trying as user account...")
repos, err = client.ListUserPublicRepos()
if err != nil {
fmt.Printf("ERROR: Failed to fetch repositories: %v\n", err)
return 1
}
}
repoNames := codeberg.GetRepoNames(repos)
fmt.Printf("Found %d public repositories on Codeberg\n", len(repoNames))
if len(repoNames) == 0 {
fmt.Println("No public repositories found")
return 0
}
if flags.DryRun {
repoNames = filterDryRunRepoNames(repoNames, flags)
}
repoNames = shuffledRepoNames(repoNames)
// Show the repositories that will be synced
showReposToSync(repoNames)
if flags.DryRun {
fmt.Printf("\n[DRY RUN] Would sync %d repositories from Codeberg to GitHub\n", len(repoNames))
if flags.CreateGitHubRepos {
fmt.Println("Would create missing GitHub repositories")
}
if !flags.SyncGitHubPublic {
return 0
}
}
if !flags.DryRun {
return syncCodebergRepos(cfg, flags, repos, repoNames)
}
return 0
}
// HandleSyncGitHubPublic handles syncing all public GitHub repositories
func HandleSyncGitHubPublic(cfg *config.Config, flags *Flags) int {
githubOrg := cfg.FindGitHubOrg()
if githubOrg == nil {
fmt.Println("No GitHub organization found in configuration")
return 1
}
fmt.Printf("Fetching public repositories from GitHub user/org: %s...\n", githubOrg.Name)
client := github.NewClient(githubOrg.GitHubToken, githubOrg.Name)
if !client.HasToken() {
fmt.Println("ERROR: GitHub token required to list repositories")
fmt.Println("Set GITHUB_TOKEN env var or create ~/.gitsyncer_github_token file")
return 1
}
repos, err := client.ListPublicRepos()
if err != nil {
fmt.Printf("ERROR: Failed to fetch repositories: %v\n", err)
return 1
}
repoNames := github.GetRepoNames(repos)
fmt.Printf("Found %d public repositories on GitHub\n", len(repoNames))
if len(repoNames) == 0 {
fmt.Println("No public repositories found")
return 0
}
if flags.DryRun {
repoNames = filterDryRunRepoNames(repoNames, flags)
}
repoNames = shuffledRepoNames(repoNames)
// Show the repositories that will be synced
showReposToSync(repoNames)
if flags.DryRun {
fmt.Printf("\n[DRY RUN] Would sync %d repositories from GitHub to Codeberg\n", len(repoNames))
if flags.CreateCodebergRepos {
fmt.Println("Would create missing Codeberg repositories")
}
return 0
}
if !flags.DryRun {
return syncGitHubRepos(cfg, flags, repos, repoNames)
}
return 0
}
// Helper functions
func createGitHubRepoIfNeeded(cfg *config.Config, repoName string) error {
githubOrg := cfg.FindGitHubOrg()
if githubOrg == nil {
return nil
}
fmt.Printf("Initializing GitHub client for organization: %s\n", githubOrg.Name)
githubClient := github.NewClient(githubOrg.GitHubToken, githubOrg.Name)
if !githubClient.HasToken() {
fmt.Println("Warning: No GitHub token found. Cannot create repository.")
return nil
}
fmt.Println("Checking/creating GitHub repository...")
return githubClient.CreateRepo(repoName, fmt.Sprintf("Mirror of %s", repoName), false)
}
func createCodebergRepoIfNeeded(cfg *config.Config, repoName string) error {
codebergOrg := cfg.FindCodebergOrg()
if codebergOrg == nil {
return nil
}
fmt.Printf("Initializing Codeberg client for organization: %s\n", codebergOrg.Name)
codebergClient := codeberg.NewClient(codebergOrg.Name, codebergOrg.CodebergToken)
if !codebergClient.HasToken() {
fmt.Println("Warning: No Codeberg token found. Cannot create repository.")
return nil
}
fmt.Println("Checking/creating Codeberg repository...")
return codebergClient.CreateRepo(repoName, fmt.Sprintf("Mirror of %s", repoName), false)
}
func initGitHubClient(cfg *config.Config) *github.Client {
githubOrg := cfg.FindGitHubOrg()
if githubOrg == nil {
fmt.Println("Warning: --create-github-repos specified but no GitHub organization found in config")
return nil
}
fmt.Printf("Initializing GitHub client for organization: %s\n", githubOrg.Name)
githubClient := github.NewClient(githubOrg.GitHubToken, githubOrg.Name)
if !githubClient.HasToken() {
fmt.Println("Warning: No GitHub token found. Cannot create repositories.")
return nil
}
fmt.Println("GitHub client initialized successfully with token")
return &githubClient
}
func createRepoWithClient(client *github.Client, repoName, description string) error {
fmt.Printf("Checking/creating GitHub repository %s...\n", repoName)
return client.CreateRepo(repoName, description, false)
}
func initCodebergClient(cfg *config.Config) *codeberg.Client {
codebergOrg := cfg.FindCodebergOrg()
if codebergOrg == nil {
fmt.Println("Warning: --create-codeberg-repos specified but no Codeberg organization found in config")
return nil
}
fmt.Printf("Initializing Codeberg client for organization: %s\n", codebergOrg.Name)
codebergClient := codeberg.NewClient(codebergOrg.Name, codebergOrg.CodebergToken)
if !codebergClient.HasToken() {
fmt.Println("Warning: No Codeberg token found. Cannot create repositories.")
return nil
}
fmt.Println("Codeberg client initialized successfully with token")
return &codebergClient
}
func showReposToSync(repoNames []string) {
fmt.Println("\nRepositories to sync:")
for _, name := range repoNames {
fmt.Printf(" - %s\n", name)
}
}
func filterDryRunRepoNames(repoNames []string, flags *Flags) []string {
_, syncState, err := loadSyncState(flags.WorkDir)
if err != nil {
fmt.Printf("Warning: Failed to load sync state: %v\n", err)
}
filtered := make([]string, 0, len(repoNames))
for _, repoName := range repoNames {
decision := evaluateSyncPolicy(repoName, syncState, true, flags.Force, flags.Throttle)
if decision.Message != "" {
fmt.Println(decision.Message)
}
if decision.Skip {
continue
}
filtered = append(filtered, repoName)
}
return filtered
}
func shuffledRepoNames(repoNames []string) []string {
shuffled := append([]string(nil), repoNames...)
rand.Shuffle(len(shuffled), func(i, j int) {
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
})
return shuffled
}
func printFullSyncSeparator() {
fmt.Println("\n" + strings.Repeat("=", 70))
fmt.Println("=== Continuing with GitHub to Codeberg sync ===")
fmt.Println(strings.Repeat("=", 70) + "\n")
}
type syncExecution struct {
syncer *sync.Syncer
descCache map[string]string
stateManager *state.Manager
syncState *state.State
}
func newSyncExecution(cfg *config.Config, flags *Flags) *syncExecution {
execution := &syncExecution{
descCache: loadDescriptionCache(flags.WorkDir),
syncer: sync.New(cfg, flags.WorkDir),
}
execution.syncer.SetBackupEnabled(flags.Backup)
manager, st, err := loadSyncState(flags.WorkDir)
if err != nil {
fmt.Printf("Warning: Failed to load sync state: %v\n", err)
}
execution.stateManager = manager
execution.syncState = st
return execution
}
func (e *syncExecution) maybeSkipRepo(repoName string, flags *Flags) bool {
decision := evaluateSyncPolicy(repoName, e.syncState, flags.DryRun, flags.Force, flags.Throttle)
if decision.Message != "" {
fmt.Println(decision.Message)
}
if decision.SetNextAllowed && e.stateManager != nil && !flags.DryRun {
e.syncState.SetNextRepoSyncAllowed(repoName, decision.NextAllowed)
if err := e.stateManager.Save(e.syncState); err != nil {
fmt.Printf("Warning: Failed to save sync state: %v\n", err)
}
}
return decision.Skip
}
func (e *syncExecution) markRepoSynced(repoName string, flags *Flags) {
if e.stateManager == nil || flags.DryRun {
return
}
recordRepoSync(repoName, e.syncState, flags.Throttle)
if err := e.stateManager.Save(e.syncState); err != nil {
fmt.Printf("Warning: Failed to save sync state: %v\n", err)
}
}
func (e *syncExecution) finishDiscoveredSync(successCount int, flags *Flags) {
if err := saveDescriptionCache(flags.WorkDir, e.descCache); err != nil {
fmt.Printf("Warning: Failed to save descriptions cache: %v\n", err)
}
fmt.Printf("\n=== Summary ===\n")
fmt.Printf("Successfully synced: %d repositories\n", successCount)
if summary := e.syncer.GenerateAbandonedBranchSummary(); summary != "" {
fmt.Print(summary)
}
printDeleteScript(e.syncer)
}
func printDeleteScript(syncer *sync.Syncer) {
if scriptPath, err := syncer.GenerateDeleteScript(); err != nil {
fmt.Printf("\n⚠️ Failed to generate script: %v\n", err)
} else if scriptPath != "" {
fmt.Printf("\n")
fmt.Print(strings.Repeat("=", 70))
fmt.Printf("\n📋 ABANDONED BRANCH MANAGEMENT SCRIPT\n")
fmt.Print(strings.Repeat("=", 70))
fmt.Printf("\n")
fmt.Printf("Generated script: %s\n", scriptPath)
fmt.Printf("\n")
fmt.Printf("Usage:\n")
fmt.Printf(" bash %s --review # Review diffs before deletion\n", scriptPath)
fmt.Printf(" bash %s --review-full # Review full diffs\n", scriptPath)
fmt.Printf(" bash %s --dry-run # Preview what will be deleted\n", scriptPath)
fmt.Printf(" bash %s # Delete branches (with confirmation)\n", scriptPath)
fmt.Printf("\n")
fmt.Printf("💡 Recommended workflow:\n")
fmt.Printf(" 1. Review branches: bash %s --review\n", scriptPath)
fmt.Printf(" 2. Dry-run delete: bash %s --dry-run\n", scriptPath)
fmt.Printf(" 3. Delete branches: bash %s\n", scriptPath)
fmt.Printf("\n")
fmt.Printf("⚠️ WARNING: Review carefully before deleting branches!\n")
fmt.Print(strings.Repeat("=", 70))
fmt.Printf("\n")
}
}
func syncCodebergRepos(cfg *config.Config, flags *Flags, repos []codeberg.Repository, repoNames []string) int {
// Initialize GitHub client if needed
var githubClient github.Client
var hasGithubClient bool
if flags.CreateGitHubRepos {
if client := initGitHubClient(cfg); client != nil {
githubClient = *client
hasGithubClient = true
}
}
fmt.Printf("\nStarting sync of %d repositories...\n", len(repoNames))
execution := newSyncExecution(cfg, flags)
successCount := 0
// Create map for descriptions
repoMap := make(map[string]codeberg.Repository)
for _, repo := range repos {
repoMap[repo.Name] = repo
}
for i, repoName := range repoNames {
fmt.Printf("\n[%d/%d] Syncing %s...\n", i+1, len(repoNames), repoName)
if execution.maybeSkipRepo(repoName, flags) {
continue
}
// Create GitHub repo if needed
if hasGithubClient && flags.CreateGitHubRepos {
codebergRepo := repoMap[repoName]
description := codebergRepo.Description
if description == "" {
description = fmt.Sprintf("Mirror of %s from Codeberg", repoName)
}
fmt.Printf("Checking/creating GitHub repository %s...\n", repoName)
err := githubClient.CreateRepo(repoName, description, false)
if err != nil {
fmt.Printf("Warning: Failed to create GitHub repo %s: %v\n", repoName, err)
}
}
if err := execution.syncer.SyncRepository(repoName); err != nil {
fmt.Printf("ERROR: Failed to sync %s: %v\n", repoName, err)
fmt.Printf("Stopping sync due to error.\n")
return 1
}
execution.markRepoSynced(repoName, flags)
successCount++
// After syncing, sync descriptions according to precedence
if cbRepo, ok := repoMap[repoName]; ok {
syncRepoDescriptions(cfg, flags.DryRun, repoName, cbRepo.Description, "", execution.descCache)
} else {
syncRepoDescriptions(cfg, flags.DryRun, repoName, "", "", execution.descCache)
}
}
execution.finishDiscoveredSync(successCount, flags)
if !flags.SyncGitHubPublic {
return 0
}
// Print separator for full sync
printFullSyncSeparator()
return 0
}
func syncGitHubRepos(cfg *config.Config, flags *Flags, repos []github.Repository, repoNames []string) int {
// Initialize Codeberg client if needed
var codebergClient codeberg.Client
var hasCodebergClient bool
if flags.CreateCodebergRepos {
if client := initCodebergClient(cfg); client != nil {
codebergClient = *client
hasCodebergClient = true
}
}
fmt.Printf("\nStarting sync of %d repositories...\n", len(repoNames))
execution := newSyncExecution(cfg, flags)
successCount := 0
// Create map for descriptions
repoMap := make(map[string]github.Repository)
for _, repo := range repos {
repoMap[repo.Name] = repo
}
for i, repoName := range repoNames {
fmt.Printf("\n[%d/%d] Syncing %s...\n", i+1, len(repoNames), repoName)
if execution.maybeSkipRepo(repoName, flags) {
continue
}
// Create Codeberg repo if needed
if hasCodebergClient && flags.CreateCodebergRepos {
githubRepo := repoMap[repoName]
description := githubRepo.Description
if description == "" {
description = fmt.Sprintf("Mirror of %s from GitHub", repoName)
}
fmt.Printf("Checking/creating Codeberg repository %s...\n", repoName)
err := codebergClient.CreateRepo(repoName, description, false)
if err != nil {
fmt.Printf("Warning: Failed to create Codeberg repo %s: %v\n", repoName, err)
}
}
if err := execution.syncer.SyncRepository(repoName); err != nil {
fmt.Printf("ERROR: Failed to sync %s: %v\n", repoName, err)
fmt.Printf("Stopping sync due to error.\n")
return 1
}
execution.markRepoSynced(repoName, flags)
successCount++
// After syncing, sync descriptions according to precedence
if ghRepo, ok := repoMap[repoName]; ok {
syncRepoDescriptions(cfg, flags.DryRun, repoName, "", ghRepo.Description, execution.descCache)
} else {
syncRepoDescriptions(cfg, flags.DryRun, repoName, "", "", execution.descCache)
}
}
execution.finishDiscoveredSync(successCount, flags)
return 0
}
// ShowFullSyncMessage displays the full sync mode message
func ShowFullSyncMessage() {
fmt.Println("Full sync mode enabled:")
fmt.Println(" - Sync all public Codeberg repos to GitHub")
fmt.Println(" - Sync all public GitHub repos to Codeberg")
fmt.Println(" - Create missing GitHub repositories")
fmt.Println(" - Create missing Codeberg repositories (when implemented)")
fmt.Println()
}
|