-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathbackups.go
90 lines (83 loc) · 2.06 KB
/
backups.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
82
83
84
85
86
87
88
89
90
package main
import (
"archive/tar"
"encoding/json"
"github.com/gosimple/slug"
"github.com/jcwillox/emerald"
"io"
"os"
"path/filepath"
"strconv"
"strings"
)
func RenameBackups(noSlugify bool) (func(), error) {
renamed := make(map[string]string)
files, err := filepath.Glob(filepath.Join(BackupPath, "*.tar"))
if err != nil {
return nil, err
}
for _, file := range files {
config, err := GetBackupConfig(file)
if err != nil {
return nil, err
}
if config == nil {
continue
}
var friendlyName string
if noSlugify {
friendlyName = config.Name + ".tar"
} else {
friendlyName = ReplaceUnderscores(slug.Make(config.Name)) + ".tar"
}
// we only want to rename backups that are named with their slug
fileName := strings.TrimSuffix(filepath.Base(file), ".tar")
dest := filepath.Join(BackupPath, friendlyName)
if fileName == config.Slug {
if stat, _ := os.Stat(dest); stat == nil {
err := os.Rename(file, dest)
if err != nil {
Errorln("failed to rename backup", emerald.HighlightPathStat(file), Arrow, emerald.HighlightPathStat(dest))
return nil, err
}
renamed[file] = dest
}
}
}
Infoln("renamed", boldCyan(strconv.Itoa(len(renamed))), emerald.Green+"backups")
return func() {
for file, dest := range renamed {
err := os.Rename(dest, file)
if err != nil {
Errorln("failed to unrename backup", emerald.HighlightPathStat(dest), Arrow, emerald.HighlightPathStat(file))
}
}
Infoln("unrenamed", boldCyan(strconv.Itoa(len(renamed))), emerald.Green+"backups")
}, err
}
func GetBackupConfig(file string) (*BackupConfig, error) {
reader, err := os.Open(file)
defer reader.Close()
if err != nil {
return nil, err
}
tr := tar.NewReader(reader)
for {
header, err := tr.Next()
if err == io.EOF {
return nil, nil
}
if err != nil {
return nil, err
}
if header.Name == "./backup.json" || header.Name == "./snapshot.json" {
data, err := io.ReadAll(tr)
if err != nil {
return nil, err
}
config := &BackupConfig{}
err = json.Unmarshal(data, config)
return config, err
}
}
}