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
|
// Copyright (C) 2014 Jakob Borg and other contributors. All rights reserved.
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file.
package versioner
import (
"os"
"path/filepath"
"sort"
"strconv"
"time"
"github.com/calmh/syncthing/osutil"
)
func init() {
// Register the constructor for this type of versioner with the name "simple"
Factories["simple"] = NewSimple
}
// The type holds our configuration
type Simple struct {
keep int
}
// The constructor function takes a map of parameters and creates the type.
func NewSimple(params map[string]string) Versioner {
keep, err := strconv.Atoi(params["keep"])
if err != nil {
keep = 5 // A reasonable default
}
s := Simple{
keep: keep,
}
if debug {
l.Debugf("instantiated %#v", s)
}
return s
}
// Move away the named file to a version archive. If this function returns
// nil, the named file does not exist any more (has been archived).
func (v Simple) Archive(path string) error {
_, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
return nil
}
if debug {
l.Debugln("archiving", path)
}
file := filepath.Base(path)
dir := filepath.Join(filepath.Dir(path), ".stversions")
err = os.MkdirAll(dir, 0755)
if err != nil && !os.IsExist(err) {
return err
} else {
osutil.HideFile(dir)
}
ver := file + "~" + time.Now().Format("20060102-150405")
err = osutil.Rename(path, filepath.Join(dir, ver))
if err != nil {
return err
}
versions, err := filepath.Glob(filepath.Join(dir, file+"~*"))
if err != nil {
l.Warnln(err)
return nil
}
if len(versions) > v.keep {
sort.Strings(versions)
for _, toRemove := range versions[:len(versions)-v.keep] {
err = os.Remove(toRemove)
if err != nil {
l.Warnln(err)
}
}
}
return nil
}
|