-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup.go
More file actions
69 lines (55 loc) · 1.33 KB
/
backup.go
File metadata and controls
69 lines (55 loc) · 1.33 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
package main
import (
"os"
"path/filepath"
"sort"
"time"
)
const maxBackups = 10
// backupFiles copies files that would be overwritten to a timestamped backup directory.
// Returns the backup directory path and the number of files backed up.
func backupFiles(pairs []FilePair, backupBase string) (string, int, error) {
timestamp := time.Now().Format("2006-01-02T15-04-05")
backupDir := filepath.Join(backupBase, timestamp)
count := 0
for _, p := range pairs {
// Only back up if the destination file already exists
if !fileExists(p.Dst) {
continue
}
backupDst := filepath.Join(backupDir, p.RelPath)
if err := copyFile(p.Dst, backupDst); err != nil {
return "", 0, err
}
count++
}
if count == 0 {
return "", 0, nil
}
return backupDir, count, nil
}
// pruneBackups keeps only the most recent `keep` backup directories.
func pruneBackups(backupBase string, keep int) error {
if !dirExists(backupBase) {
return nil
}
entries, err := os.ReadDir(backupBase)
if err != nil {
return err
}
var dirs []string
for _, e := range entries {
if e.IsDir() {
dirs = append(dirs, e.Name())
}
}
if len(dirs) <= keep {
return nil
}
sort.Strings(dirs) // timestamps sort lexicographically
// Remove oldest
for _, d := range dirs[:len(dirs)-keep] {
os.RemoveAll(filepath.Join(backupBase, d))
}
return nil
}