-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.go
279 lines (246 loc) · 6.26 KB
/
backup.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
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
// Package backup copies files to target directories based on plain text configuration.
package backup
import (
"errors"
"fmt"
"io"
"io/fs"
"math"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
var (
destDirPerm fs.FileMode = 0770
isWin = runtime.GOOS == "windows"
commentRex = regexp.MustCompile(`^#`)
targetRex = regexp.MustCompile(`^=>\s*(.*)`)
maxAgeRex = regexp.MustCompile(`^!@\s*(.*)\s*$`)
maxSizeRex = regexp.MustCompile(`^!>\s*(.*)\s*$`)
excludeRex = regexp.MustCompile(`^!\s*(.*)`)
extendExcludeRex = regexp.MustCompile(`^!\+\s*(.*)`)
printDotFileCount = 100
maxErrors = 100
)
// Data passed around during backup.
type backupContext struct {
out io.Writer
dryRun bool
targetPath string
startDate time.Time
maxSize int64
exclude []*regexp.Regexp
count backupCounts
msgs []string
}
// Stats for a directory source.
type backupCounts struct {
dir int
files int
copied int
}
// Invoke this function to perform a backup.
// config contains lines of configuration, out is a writer to send output
// messages to, and dryRun turns on dry-run mode.
//
// See details at https://github.com/borsosl/go-local-backup/README.md
func Backup(config []string, out io.Writer, dryRun bool) (ev error) {
ev = nil
ctx := backupContext{
out: out,
dryRun: dryRun,
startDate: time.Time{},
maxSize: math.MaxInt64,
}
defer func() {
if r := recover(); r != nil {
fmt.Fprintln(out, r)
}
if len(ctx.msgs) > 0 {
fmt.Fprintf(out, "\n%d errors:\n", len(ctx.msgs))
for _, s := range ctx.msgs {
fmt.Fprintln(out, s)
}
ev = fmt.Errorf("%d errors", len(ctx.msgs))
}
}()
for _, line := range config {
line = strings.TrimSpace(line)
if processNonPathLine(&ctx, line) {
continue
}
if ctx.targetPath == "" {
errText := "target path must be specified before any source paths"
fmt.Fprintln(out, "FATAL:", errText)
return errors.New(errText)
}
path := line
info, err := stat(path)
if err != nil {
msg(&ctx, fmt.Sprint("Cannot stat, skipping: ", path))
continue
}
fmt.Fprintf(out, "\n%s\n", path)
if info.IsDir() {
handleDir(&ctx, path)
} else {
handleFile(&ctx, path, info)
}
}
return
}
// Processes configuration lines that are not source locations.
func processNonPathLine(ctx *backupContext, line string) bool {
if line == "" || commentRex.MatchString(line) {
return true
}
res := targetRex.FindSubmatch([]byte(line))
if res != nil {
ctx.targetPath = strings.TrimSuffix(string(res[1]), string(filepath.Separator))
fmt.Fprintln(ctx.out, "target", ctx.targetPath)
return true
}
res = maxAgeRex.FindSubmatch([]byte(line))
if res != nil {
max, err := strconv.Atoi(string(res[1]))
if err != nil {
fmt.Fprintf(ctx.out, "WARN: Expected only number in: %s\n", line)
} else {
sub := time.Duration(max) * 24 * time.Hour
ctx.startDate = time.Now().Add(-sub)
y, m, d := ctx.startDate.Date()
ctx.startDate = time.Date(y, m, d, 0, 0, 0, 0, ctx.startDate.Location())
fmt.Fprintln(ctx.out, "since", ctx.startDate)
}
return true
}
res = maxSizeRex.FindSubmatch([]byte(line))
if res != nil {
max, err := strconv.ParseInt(string(res[1]), 10, 64)
if err != nil {
fmt.Fprintf(ctx.out, "WARN: Expected only number in: %s\n", line)
} else {
ctx.maxSize = max
fmt.Fprintln(ctx.out, "max size", ctx.maxSize)
}
return true
}
res = extendExcludeRex.FindSubmatch([]byte(line))
if res != nil {
parseExclude(ctx, string(res[1]), true)
fmt.Fprintln(ctx.out, "extend exclude", string(res[1]))
return true
}
res = excludeRex.FindSubmatch([]byte(line))
if res != nil {
parseExclude(ctx, string(res[1]), false)
fmt.Fprintln(ctx.out, "exclude", string(res[1]))
return true
}
return false
}
// Collects active regular expressions for exclusion.
func parseExclude(ctx *backupContext, arg string, extend bool) {
if !extend {
ctx.exclude = nil
}
arg = strings.TrimSpace(arg)
parts := strings.Split(arg, ",,")
for _, part := range parts {
if part == "" {
continue
}
rex, err := regexp.Compile(part)
if err != nil {
msg(ctx, fmt.Sprintf("Error in exlude regexp: %s", part))
} else {
ctx.exclude = append(ctx.exclude, rex)
}
}
}
// Recurses a source directory, filters excluded subdirectories.
func handleDir(ctx *backupContext, path string) {
ctx.count = backupCounts{}
walkCallback := func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
path += string(filepath.Separator)
for _, rex := range ctx.exclude {
if rex.MatchString(path) {
return fs.SkipDir
}
}
ctx.count.dir++
} else {
info, err := d.Info()
if err == nil {
handleFile(ctx, path, info)
}
}
return nil
}
walkDir(path, walkCallback)
if ctx.count.files >= printDotFileCount {
fmt.Fprintln(ctx.out)
}
fmt.Fprintf(ctx.out, "Dirs: %d, Files: %d, Copied: %d\n",
ctx.count.dir, ctx.count.files, ctx.count.copied)
}
// Copies a file if not filtered.
func handleFile(ctx *backupContext, srcPath string, srcInfo fs.FileInfo) {
ctx.count.files++
if !ctx.dryRun && ctx.count.files%printDotFileCount == 0 {
fmt.Fprint(ctx.out, ".")
}
if srcInfo.Mode()&fs.ModeSymlink != 0 {
return
}
if srcInfo.Size() > ctx.maxSize {
return
}
if srcInfo.ModTime().Before(ctx.startDate) {
return
}
for _, rex := range ctx.exclude {
if rex.MatchString(srcPath) {
return
}
}
vol := filepath.VolumeName(srcPath)
destPath := ctx.targetPath + srcPath[len(vol):]
destInfo, err := stat(destPath)
if err == nil {
if !destInfo.ModTime().Before(srcInfo.ModTime()) {
return
}
if isWin && destInfo.Mode()&0200 != 0 {
chmod(destPath, destDirPerm)
}
} else if !ctx.dryRun {
err := mkdirAll(filepath.Dir(destPath), destDirPerm)
if err != nil {
msg(ctx, fmt.Sprint("Cannot create dirs for: ", destPath))
return
}
}
if ctx.dryRun {
fmt.Fprintln(ctx.out, srcPath)
ctx.count.copied++
return
}
err = copy(srcPath, destPath, srcInfo)
if err != nil {
msg(ctx, err.Error())
return
}
ctx.count.copied++
}
// Adds to collected messages that are printed after sources are processed.
func msg(ctx *backupContext, msg string) {
ctx.msgs = append(ctx.msgs, msg)
if len(ctx.msgs) >= maxErrors {
panic("Quitting due to too many errors!")
}
}