-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (62 loc) · 1.49 KB
/
main.go
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
package main
import (
"fmt"
"os"
"os/user"
"path"
"path/filepath"
"runtime"
"time"
"github.com/akyoto/color"
"github.com/mholt/archiver"
)
const (
interval = 2 * time.Hour
deleteThreshold = 48 * time.Hour
)
func main() {
sourceDirectory, targetDirectory := setup()
for {
deleteOldFiles(targetDirectory)
backup(sourceDirectory, targetDirectory)
runtime.GC()
time.Sleep(interval)
}
}
func setup() (string, string) {
user, err := user.Current()
if err != nil {
panic(err)
}
sourceDirectory := path.Join(user.HomeDir, ".aero/db/")
targetDirectory := path.Join(user.HomeDir, ".aero/backups/")
// Create directory in case it doesn't exist
os.MkdirAll(targetDirectory, 0777)
return sourceDirectory, targetDirectory
}
func backup(sourceDirectory, targetDirectory string) {
timestamp := time.Now().UTC().Format(time.RFC3339)
outFileName := "db-" + timestamp + ".tar.xz"
outFilePath := path.Join(targetDirectory, outFileName)
color.Yellow("Creating backup %s", outFilePath)
err := archiver.Archive([]string{sourceDirectory}, outFilePath)
if err != nil {
color.Red(err.Error())
}
color.Green("Finished.")
}
func deleteOldFiles(targetDirectory string) {
filepath.Walk(targetDirectory, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if time.Since(info.ModTime()) > deleteThreshold {
color.Red("Deleting old backup %s", path)
err := os.Remove(path)
if err != nil {
fmt.Println(err)
}
}
return nil
})
}