-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbundles.go
More file actions
1151 lines (934 loc) · 34.9 KB
/
Copy pathbundles.go
File metadata and controls
1151 lines (934 loc) · 34.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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//nolint:wsl_v5 // extensive whitespace linting would require significant refactoring
package githosts
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"time"
"gitlab.com/tozd/go/errors"
)
const (
bundleExtension = ".bundle"
lfsArchiveExtension = ".lfs.tar.gz"
manifestExtension = ".manifest"
// invalidBundleStringCheck checks for a portion of the following in the command output
// to determine if valid: "does not look like a v2 or v3 bundle file".
invalidBundleStringCheck = "does not look like"
bundleTimestampChars = 14
minBundleFileNameTokens = 3
)
func getLatestBundlePath(backupPath string) (string, error) {
bFiles, err := getBundleFiles(backupPath)
if err != nil {
return "", fmt.Errorf("failed to get bundle files: %w", err)
}
if len(bFiles) == 0 {
// No valid bundle files found - this could be because all bundles have invalid timestamps
// Return a specific error that callers can handle appropriately
return "", errors.New("no valid bundle files found in path")
}
// get timestamps in filenames for sorting
fNameTimes := map[string]int{}
for _, f := range bFiles {
var ts int
if ts, err = getTimeStampPartFromFileName(f.info.Name()); err == nil {
fNameTimes[f.info.Name()] = ts
continue
}
}
type kv struct {
Key string
Value int
}
ss := make([]kv, 0, len(fNameTimes))
for k, v := range fNameTimes {
ss = append(ss, kv{k, v})
}
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value
})
return filepath.Join(backupPath, ss[0].Key), nil
}
func getBundleRefs(ctx context.Context, bundlePath string) (gitRefs, error) {
bundleRefsCmd := exec.CommandContext(ctx, "git", "bundle", "list-heads", bundlePath)
out, bundleRefsCmdErr := bundleRefsCmd.CombinedOutput()
if bundleRefsCmdErr != nil {
gitErr := parseGitError(out)
if gitErr != "" {
return nil, errors.Errorf("git bundle list-heads failed: %s", gitErr)
}
return nil, errors.Wrap(bundleRefsCmdErr, "git bundle list-heads failed")
}
refs := generateMapFromRefsCmdOutput(out)
return refs, nil
}
func dirHasBundles(dir string) bool {
entries, err := os.ReadDir(dir)
if err != nil {
return false
}
for _, entry := range entries {
name := entry.Name()
// Check for both regular and encrypted bundles
if strings.HasSuffix(name, bundleExtension) ||
strings.HasSuffix(name, bundleExtension+encryptedBundleExtension) {
return true
}
}
return false
}
// lfsArchiveExistsForLatestBundle checks if an LFS archive exists for the latest bundle
func lfsArchiveExistsForLatestBundle(backupPath, repoName string) (bool, error) {
// Get the latest bundle path to extract its timestamp
latestBundlePath, err := getLatestBundlePath(backupPath)
if err != nil {
return false, fmt.Errorf("failed to get latest bundle path: %w", err)
}
// Extract timestamp from bundle filename
bundleBasename := filepath.Base(latestBundlePath)
timestamp, err := getTimeStampPartFromFileName(bundleBasename)
if err != nil {
return false, fmt.Errorf("failed to extract timestamp from bundle name: %w", err)
}
// Construct expected LFS archive filename
timestampStr := fmt.Sprintf("%014d", timestamp)
expectedLFSArchive := repoName + "." + timestampStr + lfsArchiveExtension
expectedLFSPath := filepath.Join(backupPath, expectedLFSArchive)
// Check if LFS archive exists
_, err = os.Stat(expectedLFSPath)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, fmt.Errorf("failed to check LFS archive existence: %w", err)
}
return true, nil
}
func getLatestBundleRefs(ctx context.Context, backupPath, encryptionPassphrase string) (gitRefs, error) {
// if we encounter an invalid bundle, then we need to repeat until we find a valid one or run out
for {
path, err := getLatestBundlePath(backupPath)
if err != nil {
// If no valid bundles found (e.g., all have invalid timestamps),
// return nil refs which will cause remoteRefsMatchLocalRefs to return false
// and allow the backup to proceed
if strings.Contains(err.Error(), "no valid bundle files found") {
logger.Printf("no valid bundles found for ref comparison: %s", err)
return nil, nil
}
return nil, err
}
// Check if this is an encrypted bundle
//nolint:nestif // complex encryption logic requires nested conditions
if isEncryptedBundle(path) {
// For encrypted bundles, try to read refs from manifest if passphrase is available
if encryptionPassphrase == "" {
// No passphrase provided but bundle is encrypted - force creation of unencrypted bundle
return nil, fmt.Errorf("encrypted bundle found but no passphrase provided - will create unencrypted bundle")
}
// Try to read refs from encrypted manifest
manifest, manifestErr := readBundleManifestWithPassphrase(path, encryptionPassphrase)
if manifestErr == nil && manifest != nil && len(manifest.GitRefs) > 0 {
// Successfully read refs from encrypted manifest
return manifest.GitRefs, nil
}
// If manifest reading fails, fall back to decrypting bundle and reading refs directly
logger.Printf("could not read refs from encrypted manifest for %s, will decrypt bundle temporarily", path)
// Create temporary file for decryption
tempFile, tempErr := os.CreateTemp("", "bundle-decrypt-*.bundle")
if tempErr != nil {
return nil, fmt.Errorf("failed to create temp file for bundle decryption: %w", tempErr)
}
tempPath := tempFile.Name()
tempFile.Close()
defer os.Remove(tempPath)
// Decrypt the bundle temporarily
if decryptErr := decryptFile(path, tempPath, encryptionPassphrase); decryptErr != nil {
return nil, fmt.Errorf("failed to decrypt bundle for ref reading: %w", decryptErr)
}
// Read refs from decrypted bundle
if refs, refsErr := getBundleRefs(ctx, tempPath); refsErr == nil {
return refs, nil
} else {
// Check if it's an invalid bundle
if strings.Contains(refsErr.Error(), invalidBundleStringCheck) {
// rename the invalid bundle
logger.Printf("renaming invalid encrypted bundle to %s.invalid", path)
if err = os.Rename(path, path+".invalid"); err != nil {
// failed to rename, meaning a filesystem or permissions issue
return nil, fmt.Errorf("failed to rename invalid bundle %w", err)
}
// invalid bundle rename, so continue to check for the next latest bundle
continue
}
return nil, refsErr
}
} else {
// Unencrypted bundle - use existing logic
var refs gitRefs
if refs, err = getBundleRefs(ctx, path); err != nil {
// failed to get refs
if strings.Contains(err.Error(), invalidBundleStringCheck) {
// rename the invalid bundle
logger.Printf("renaming invalid bundle to %s.invalid", path)
if err = os.Rename(path, path+".invalid"); err != nil {
// failed to rename, meaning a filesystem or permissions issue
return nil, fmt.Errorf("failed to rename invalid bundle %w", err)
}
// invalid bundle rename, so continue to check for the next latest bundle
continue
}
return nil, fmt.Errorf("failed to read bundle %w", err)
}
// otherwise return the refs
return refs, nil
}
}
}
func createBundle(ctx context.Context, logLevel int, workingPath string, repo repository, encryptionPassphrase string) errors.E {
objectsPath := filepath.Join(workingPath, "objects")
dirs, readErr := os.ReadDir(objectsPath)
if readErr != nil {
return errors.Errorf("failed to read objectsPath: %s: %s", objectsPath, readErr)
}
emptyClone, err := isEmpty(ctx, workingPath)
if err != nil {
return errors.Errorf("failed to check if clone is empty: %s", err)
}
if len(dirs) == 2 && emptyClone {
return errors.Errorf("%s is empty", repo.PathWithNameSpace)
}
timestamp := getTimestamp()
backupFile := repo.Name + "." + timestamp + bundleExtension
// Create bundle in working directory first
workingBundlePath := filepath.Join(workingPath, backupFile)
logger.Printf("creating bundle for: %s", repo.Name)
bundleCmd := exec.CommandContext(ctx, "git", "bundle", "create", workingBundlePath, "--all")
bundleCmd.Dir = workingPath
var bundleOut bytes.Buffer
bundleCmd.Stdout = &bundleOut
bundleCmd.Stderr = &bundleOut
startBundle := time.Now()
if bundleErr := bundleCmd.Run(); bundleErr != nil {
return errors.Errorf("failed to create bundle: %s: %s", repo.Name, bundleErr)
}
if logLevel > 0 {
logger.Printf("git bundle create time for %s %s: %s", repo.Domain, repo.Name, time.Since(startBundle).String())
}
// Encrypt the bundle if a passphrase is provided
//nolint:nestif // encryption logic requires nested conditions for proper error handling
if encryptionPassphrase != "" {
// Create manifest file in working directory (only for encrypted bundles)
if manifestErr := createBundleManifest(ctx, workingBundlePath, timestamp); manifestErr != nil {
logger.Printf("warning: failed to create manifest for bundle %s: %s", backupFile, manifestErr)
// Don't fail the bundle creation if manifest fails
}
encryptedBundlePath := workingBundlePath + encryptedBundleExtension
logger.Printf("encrypting bundle: %s", backupFile)
if err := encryptFile(workingBundlePath, encryptedBundlePath, encryptionPassphrase); err != nil {
return errors.Errorf("failed to encrypt bundle: %s", err)
}
// Remove the unencrypted bundle after successful encryption
if err := os.Remove(workingBundlePath); err != nil {
logger.Printf("warning: failed to remove unencrypted bundle: %s", err)
// Don't fail - we have the encrypted version
}
// Also encrypt the manifest if it exists
manifestPath := strings.TrimSuffix(workingBundlePath, bundleExtension) + manifestExtension
if _, err := os.Stat(manifestPath); err == nil {
encryptedManifestPath := manifestPath + encryptedBundleExtension
if err := encryptFile(manifestPath, encryptedManifestPath, encryptionPassphrase); err != nil {
logger.Printf("warning: failed to encrypt manifest: %s", err)
// Don't fail the bundle creation if manifest encryption fails
} else {
// Remove unencrypted manifest after successful encryption
if err := os.Remove(manifestPath); err != nil {
logger.Printf("warning: failed to remove unencrypted manifest: %s", err)
}
}
}
}
return nil
}
func createLFSArchive(ctx context.Context, logLevel int, workingPath, backupPath string, repo repository, encryptionPassphrase string) errors.E {
timestamp := getTimestamp()
archiveFile := repo.Name + "." + timestamp + lfsArchiveExtension
archiveFilePath := filepath.Join(backupPath, archiveFile)
createErr := createDirIfAbsent(backupPath)
if createErr != nil {
return errors.Errorf("failed to create backup path: %s: %s", backupPath, createErr)
}
logger.Printf("creating git lfs archive for: %s", repo.Name)
tarCmd := exec.CommandContext(ctx, "tar", "-czf", archiveFilePath, "lfs")
tarCmd.Dir = workingPath
var tarOut bytes.Buffer
tarCmd.Stdout = &tarOut
tarCmd.Stderr = &tarOut
startTar := time.Now()
if tarErr := tarCmd.Run(); tarErr != nil {
tarErr = fmt.Errorf("repo name: %s: %s: %w", repo.Name, strings.TrimSpace(tarOut.String()), tarErr)
return errors.Errorf("failed to create git lfs archive: %s: %s", repo.Name, tarErr)
}
if logLevel > 0 {
logger.Printf("git lfs archive create time for %s %s: %s", repo.Domain, repo.Name, time.Since(startTar).String())
}
// Create manifest file for LFS archive (only for encrypted archives)
if encryptionPassphrase != "" {
if manifestErr := createLFSManifest(archiveFilePath, timestamp); manifestErr != nil {
logger.Printf("warning: failed to create manifest for LFS archive %s: %s", archiveFile, manifestErr)
// Don't fail the archive creation if manifest fails
}
}
return nil
}
func createLFSArchiveWithTimestamp(ctx context.Context, logLevel int, workingPath, backupPath string, repo repository, timestamp string, encryptionPassphrase string) errors.E {
archiveFile := repo.Name + "." + timestamp + lfsArchiveExtension
archiveFilePath := filepath.Join(backupPath, archiveFile)
createErr := createDirIfAbsent(backupPath)
if createErr != nil {
return errors.Errorf("failed to create backup path: %s: %s", backupPath, createErr)
}
logger.Printf("creating git lfs archive for: %s", repo.Name)
tarCmd := exec.CommandContext(ctx, "tar", "-czf", archiveFilePath, "lfs")
tarCmd.Dir = workingPath
var tarOut bytes.Buffer
tarCmd.Stdout = &tarOut
tarCmd.Stderr = &tarOut
startTar := time.Now()
if tarErr := tarCmd.Run(); tarErr != nil {
tarErr = fmt.Errorf("repo name: %s: %s: %w", repo.Name, strings.TrimSpace(tarOut.String()), tarErr)
return errors.Errorf("failed to create git lfs archive: %s: %s", repo.Name, tarErr)
}
if logLevel > 0 {
logger.Printf("git lfs archive create time for %s %s: %s", repo.Domain, repo.Name, time.Since(startTar).String())
}
// Create manifest file for LFS archive (only for encrypted archives)
if encryptionPassphrase != "" {
if manifestErr := createLFSManifest(archiveFilePath, timestamp); manifestErr != nil {
logger.Printf("warning: failed to create manifest for LFS archive %s: %s", archiveFile, manifestErr)
// Don't fail the archive creation if manifest fails
}
}
return nil
}
// renameBundleAsInvalid renames a bundle file with an invalid timestamp to have .invalid extension
// If the bundle is encrypted and has a manifest, the manifest is also renamed
func renameBundleAsInvalid(backupPath, bundleFileName string) error {
oldPath := filepath.Join(backupPath, bundleFileName)
newPath := oldPath + ".invalid"
// Rename the bundle file
if err := os.Rename(oldPath, newPath); err != nil {
return fmt.Errorf("failed to rename bundle file: %w", err)
}
// Check if this is an encrypted bundle that might have a manifest
if strings.HasSuffix(bundleFileName, bundleExtension+encryptedBundleExtension) {
// Get the manifest filename by replacing .bundle.age with .manifest.age
manifestName := strings.TrimSuffix(bundleFileName, bundleExtension+encryptedBundleExtension) + manifestExtension + encryptedBundleExtension
manifestOldPath := filepath.Join(backupPath, manifestName)
// Check if manifest exists
if _, err := os.Stat(manifestOldPath); err == nil {
// Manifest exists, rename it too
manifestNewPath := manifestOldPath + ".invalid"
if err := os.Rename(manifestOldPath, manifestNewPath); err != nil {
logger.Printf("warning: failed to rename manifest file '%s': %s", manifestName, err)
// Don't return error here as the bundle was already renamed
}
}
}
return nil
}
// cleanupInvalidBundles scans the backup directory and renames any bundles with invalid timestamps
// This ensures old invalid bundles don't cause issues during backup operations
func cleanupInvalidBundles(backupPath string) {
// Check if directory exists
if _, err := os.Stat(backupPath); os.IsNotExist(err) {
return
}
// Read directory
files, err := os.ReadDir(backupPath)
if err != nil {
return
}
for _, f := range files {
name := f.Name()
// Skip already marked invalid files
if strings.HasSuffix(name, ".invalid") {
continue
}
// Check for both regular and encrypted bundles
isBundleFile := strings.HasSuffix(name, bundleExtension)
isEncryptedBundleFile := strings.HasSuffix(name, bundleExtension+encryptedBundleExtension)
if !isBundleFile && !isEncryptedBundleFile {
continue
}
// For encrypted bundles, we need to get the timestamp from the original bundle name
bundleName := name
if isEncryptedBundleFile {
bundleName = getOriginalBundleName(name)
}
// Check if timestamp is valid
_, err := timeStampFromBundleName(bundleName)
if err != nil {
// Bundle has invalid date - rename it
logger.Printf("cleaning up bundle with invalid timestamp: %s", name)
if renameErr := renameBundleAsInvalid(backupPath, name); renameErr != nil {
logger.Printf("failed to rename invalid bundle '%s': %s", name, renameErr)
}
}
}
}
func getBundleFiles(backupPath string) (bundleFiles, error) {
files, err := os.ReadDir(backupPath)
if err != nil {
return nil, errors.Wrap(err, "backup path read failed")
}
var bfs bundleFiles
for _, f := range files {
name := f.Name()
// Skip already marked invalid files
if strings.HasSuffix(name, ".invalid") {
continue
}
// Check for both regular and encrypted bundles
isBundleFile := strings.HasSuffix(name, bundleExtension)
isEncryptedBundleFile := strings.HasSuffix(name, bundleExtension+encryptedBundleExtension)
if !isBundleFile && !isEncryptedBundleFile {
continue
}
var ts time.Time
// For encrypted bundles, we need to get the timestamp from the original bundle name
bundleName := name
if isEncryptedBundleFile {
bundleName = getOriginalBundleName(name)
}
ts, err = timeStampFromBundleName(bundleName)
if err != nil {
// Bundle has invalid date - rename it
logger.Printf("bundle '%s' has invalid timestamp, marking as invalid: %s", name, err)
if renameErr := renameBundleAsInvalid(backupPath, name); renameErr != nil {
logger.Printf("failed to rename invalid bundle '%s': %s", name, renameErr)
// Even if rename fails, skip this bundle to avoid blocking the process
}
continue
}
var info os.FileInfo
info, err = f.Info()
if err != nil {
return nil, fmt.Errorf("failed to get info for file %s: %w", f.Name(), err)
}
bfs = append(bfs, bundleFile{
info: info,
created: ts,
})
}
sort.Sort(bfs)
return bfs, nil
}
func pruneBackups(backupPath string, keep int) errors.E {
files, readErr := os.ReadDir(backupPath)
if readErr != nil {
return errors.Wrap(readErr, "backup path read failed")
}
if len(files) > 0 {
logger.Printf("pruning %s to keep %d newest only", backupPath, keep)
}
var bfs bundleFiles
for _, f := range files {
// Skip already marked invalid files
if strings.HasSuffix(f.Name(), ".invalid") {
continue
}
name := f.Name()
// Check for both regular and encrypted bundles
isBundleFile := strings.HasSuffix(name, bundleExtension)
isEncryptedBundleFile := strings.HasSuffix(name, bundleExtension+encryptedBundleExtension)
if !isBundleFile && !isEncryptedBundleFile {
// no need to mention skipping lfs archives, as they are not bundles
if !strings.HasSuffix(name, lfsArchiveExtension) && !strings.HasSuffix(name, manifestExtension) &&
!strings.HasSuffix(name, manifestExtension+encryptedBundleExtension) {
logger.Printf("skipping non bundle, non lfs, and non-manifest archive file '%s'", name)
}
continue
}
var ts time.Time
// For encrypted bundles, we need to get the timestamp from the original bundle name
bundleName := name
if isEncryptedBundleFile {
bundleName = getOriginalBundleName(name)
}
ts, err := timeStampFromBundleName(bundleName)
if err != nil {
// Bundle has invalid date - rename it during pruning
logger.Printf("bundle '%s' has invalid timestamp during pruning, marking as invalid: %s", name, err)
if renameErr := renameBundleAsInvalid(backupPath, name); renameErr != nil {
logger.Printf("failed to rename invalid bundle '%s': %s", name, renameErr)
// Even if rename fails, skip this bundle to avoid blocking the process
}
continue
}
var info os.FileInfo
info, infoErr := f.Info()
if infoErr != nil {
return errors.Wrap(infoErr, "failed to get file info")
}
bfs = append(bfs, bundleFile{
info: info,
created: ts,
})
}
sort.Sort(bfs)
firstFilesToDelete := len(bfs) - keep
for x, f := range files {
if x < firstFilesToDelete {
if removeErr := os.Remove(filepath.Join(backupPath, f.Name())); removeErr != nil {
return errors.Wrap(removeErr, "failed to remove file")
}
continue
}
break
}
return nil
}
type bundleFile struct {
info os.FileInfo
created time.Time
}
type bundleFiles []bundleFile
func (b bundleFiles) Len() int {
return len(b)
}
func (b bundleFiles) Less(i, j int) bool {
return b[i].created.Before(b[j].created)
}
func (b bundleFiles) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
func timeStampFromBundleName(i string) (time.Time, errors.E) {
tokens := strings.Split(i, ".")
if len(tokens) < minBundleFileNameTokens {
return time.Time{}, errors.New("invalid bundle name")
}
sTime := tokens[len(tokens)-2]
if len(sTime) != bundleTimestampChars {
return time.Time{}, errors.Errorf("bundle '%s' has an invalid timestamp", i)
}
return timeStampToTime(sTime)
}
func getTimeStampPartFromFileName(name string) (int, error) {
// Handle encrypted bundles by removing .age extension first
originalName := name
if isEncryptedBundle(name) {
originalName = getOriginalBundleName(name)
}
if strings.Count(originalName, ".") >= minBundleFileNameTokens-1 {
parts := strings.Split(originalName, ".")
strTimestamp := parts[len(parts)-2]
l, err := strconv.Atoi(strTimestamp)
if err != nil {
return 0, fmt.Errorf("invalid timestamp '%s': %w", name, err)
}
return l, nil
}
return 0, fmt.Errorf("filename '%s' does not match bundle format <repo-name>.<timestamp>.bundle",
name)
}
func filesIdentical(path1, path2 string) bool {
// First check if file sizes are same
latestBundleSize := getFileSize(path1)
previousBundleSize := getFileSize(path2)
// If sizes are different, files are definitely not identical
if latestBundleSize != previousBundleSize {
return false
}
// Try to use manifests for comparison if these are encrypted bundle files
// (manifests are only created for encrypted bundles)
if strings.HasSuffix(path1, bundleExtension+encryptedBundleExtension) &&
strings.HasSuffix(path2, bundleExtension+encryptedBundleExtension) {
manifest1, _ := readBundleManifest(path1)
manifest2, _ := readBundleManifest(path2)
// If both manifests exist and have hashes, use them for comparison
if manifest1 != nil && manifest2 != nil &&
manifest1.BundleHash != "" && manifest2.BundleHash != "" {
return manifest1.BundleHash == manifest2.BundleHash
}
}
// Fall back to computing hashes directly
latestBundleHash, latestHashErr := getSHA2Hash(path1)
if latestHashErr != nil {
logger.Printf("failed to get sha2 hash for: %s", path1)
return false
}
previousBundleHash, previousHashErr := getSHA2Hash(path2)
if previousHashErr != nil {
logger.Printf("failed to get sha2 hash for: %s", path2)
return false
}
return reflect.DeepEqual(latestBundleHash, previousBundleHash)
}
// checkBundleIsDuplicate checks if the bundle in workingPath is identical to the latest bundle in backupPath
// Returns the bundle filename from workingPath, whether it's a duplicate, and whether to replace existing with encrypted
func checkBundleIsDuplicate(workingPath, backupPath, encryptionPassphrase string) (string, bool, bool, error) {
// Find the bundle file in working directory (could be encrypted or not)
workingFiles, err := os.ReadDir(workingPath)
if err != nil {
return "", false, false, fmt.Errorf("failed to read working directory: %w", err)
}
var workingBundleFile string
var workingIsEncrypted bool
for _, f := range workingFiles {
name := f.Name()
if strings.HasSuffix(name, bundleExtension+encryptedBundleExtension) {
workingBundleFile = name
workingIsEncrypted = true
break
} else if strings.HasSuffix(name, bundleExtension) {
workingBundleFile = name
workingIsEncrypted = false
// Don't break - prefer encrypted if both exist
}
}
if workingBundleFile == "" {
return "", false, false, errors.New("no bundle file found in working directory")
}
workingBundlePath := filepath.Join(workingPath, workingBundleFile)
// Check if backup directory exists and has bundles
if !dirHasBundles(backupPath) {
// No existing bundles, so this is not a duplicate
return workingBundleFile, false, false, nil
}
// Get the latest bundle in backup directory
latestBackupPath, err := getLatestBundlePath(backupPath)
if err != nil {
// If we can't find a valid latest bundle (e.g., all have invalid timestamps),
// treat this as having no existing bundles - not a duplicate
logger.Printf("could not find valid bundle for comparison: %s", err)
return workingBundleFile, false, false, nil
}
backupIsEncrypted := isEncryptedBundle(latestBackupPath)
// Determine if bundles are identical
var isDuplicate bool
var shouldReplace bool
// Case 1: Both encrypted - try manifest comparison first, then file comparison
//nolint:gocritic // ifElseChain is clearer for these complex encryption scenarios
if workingIsEncrypted && backupIsEncrypted {
// Try to use manifest files for comparison if they exist
workingManifest, _ := readBundleManifestWithPassphrase(workingBundlePath, encryptionPassphrase)
backupManifest, _ := readBundleManifestWithPassphrase(latestBackupPath, encryptionPassphrase)
if workingManifest != nil && backupManifest != nil &&
workingManifest.BundleHash != "" && backupManifest.BundleHash != "" {
isDuplicate = workingManifest.BundleHash == backupManifest.BundleHash
} else {
// Fall back to file comparison if manifests are not available
isDuplicate = filesIdentical(workingBundlePath, latestBackupPath)
}
shouldReplace = false
} else if workingIsEncrypted && !backupIsEncrypted {
// Case 2: Working is encrypted, backup is not encrypted
// Need to decrypt working bundle to compare
if encryptionPassphrase != "" {
identical, err := compareEncryptedWithPlain(workingBundlePath, latestBackupPath, encryptionPassphrase)
if err != nil {
logger.Printf("warning: failed to compare encrypted with plain bundle: %s", err)
isDuplicate = false
} else {
isDuplicate = identical
}
// If identical, we should replace the unencrypted with encrypted
shouldReplace = isDuplicate
} else {
// Can't decrypt to compare, assume not duplicate
isDuplicate = false
shouldReplace = false
}
} else if !workingIsEncrypted && backupIsEncrypted {
// Case 3: Working is not encrypted, backup is encrypted
// This shouldn't happen in normal flow (we encrypted in createBundle)
// but handle it anyway - can't compare without passphrase
isDuplicate = false
shouldReplace = false
} else {
// Case 4: Both unencrypted - direct file comparison
// No manifests are created for unencrypted bundles
isDuplicate = filesIdentical(workingBundlePath, latestBackupPath)
shouldReplace = false
}
if isDuplicate {
if shouldReplace {
logger.Printf("bundle content unchanged but will replace unencrypted with encrypted version: %s",
filepath.Base(latestBackupPath))
} else {
logger.Printf("no change since previous bundle: %s", filepath.Base(latestBackupPath))
}
}
return workingBundleFile, isDuplicate, shouldReplace, nil
}
// func removeBundleIfDuplicate(dir string) bool {
// files, err := getBundleFiles(dir)
// if err != nil {
// logger.Println(err)
//
// return false
// }
//
// if len(files) == 1 {
// return false
// }
// // get timestamps in filenames for sorting
// fNameTimes := map[string]int{}
//
// for _, f := range files {
// var ts int
// if ts, err = getTimeStampPartFromFileName(f.info.Name()); err == nil {
// fNameTimes[f.info.Name()] = ts
// }
// }
//
// type kv struct {
// Key string
// Value int
// }
//
// ss := make([]kv, 0, len(fNameTimes))
//
// for k, v := range fNameTimes {
// ss = append(ss, kv{k, v})
// }
//
// sort.Slice(ss, func(i, j int) bool {
// return ss[i].Value > ss[j].Value
// })
//
// latestBundleFilePath := filepath.Join(dir, ss[0].Key)
// previousBundleFilePath := filepath.Join(dir, ss[1].Key)
//
// if filesIdentical(latestBundleFilePath, previousBundleFilePath) {
// logger.Printf("no change since previous bundle: %s", ss[1].Key)
// logger.Printf("deleting duplicate bundle: %s", ss[0].Key)
//
// if deleteFile(filepath.Join(dir, ss[0].Key)) != nil {
// logger.Println("failed to remove duplicate bundle")
// }
//
// return false
// }
//
// return true
// }
// func deleteFile(path string) error {
// if err := os.Remove(path); err != nil {
// return errors.Wrap(err, "failed to remove file")
// }
//
// return nil
//}
func getSHA2Hash(filePath string) ([]byte, error) {
var result []byte
file, err := os.Open(filePath)
if err != nil {
return result, errors.Wrap(err, "failed to open file")
}
defer func() {
if err = file.Close(); err != nil {
logger.Printf("warn: failed to close: %s", filePath)
}
}()
hash := sha256.New()
if _, err = io.Copy(hash, file); err != nil {
return result, errors.Wrap(err, "failed to get hash")
}
return hash.Sum(result), nil
}
func getFileSize(path string) int64 {
fi, err := os.Stat(path)
if err != nil {
logger.Println(err)
return 0
}
return fi.Size()
}
// BundleManifest represents the metadata for a bundle
type BundleManifest struct {
CreationTime string `json:"creation_time"`
BundleHash string `json:"bundle_hash"`
BundleFile string `json:"bundle_file"`
GitRefs map[string]string `json:"git_refs"`
}
// readBundleManifest reads a bundle manifest file and returns the manifest data
func readBundleManifest(bundlePath string) (*BundleManifest, error) {
var manifestPath string
// Handle encrypted bundles
if isEncryptedBundle(bundlePath) {
// For encrypted bundles, the manifest is also encrypted
// e.g., test-repo.20250920100845.bundle.age -> test-repo.20250920100845.manifest.age
originalBundlePath := getOriginalBundleName(bundlePath)
manifestPath = strings.TrimSuffix(originalBundlePath, bundleExtension) + manifestExtension + encryptedBundleExtension
} else {
// For regular bundles
manifestPath = strings.TrimSuffix(bundlePath, bundleExtension) + manifestExtension
}
// Check if manifest file exists
if _, err := os.Stat(manifestPath); os.IsNotExist(err) {
return nil, nil // No manifest file exists
}
var manifestData []byte
var err error
// If it's an encrypted manifest, we need the passphrase to decrypt it
if strings.HasSuffix(manifestPath, encryptedBundleExtension) {
// For encrypted manifests, we can't read them without the passphrase
// This function doesn't have access to the passphrase, so return nil
// The caller should handle encrypted manifests separately if needed
return nil, nil
}
// Read the manifest file
manifestData, err = os.ReadFile(manifestPath)
if err != nil {
return nil, fmt.Errorf("failed to read manifest file: %w", err)
}
// Unmarshal the JSON
var manifest BundleManifest
if err := json.Unmarshal(manifestData, &manifest); err != nil {
return nil, fmt.Errorf("failed to unmarshal manifest: %w", err)
}
return &manifest, nil
}
// readBundleManifestWithPassphrase reads a bundle manifest file, decrypting if necessary
func readBundleManifestWithPassphrase(bundlePath, passphrase string) (*BundleManifest, error) {
var manifestPath string