-
Notifications
You must be signed in to change notification settings - Fork 312
/
file.go
64 lines (53 loc) · 1.37 KB
/
file.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
package file
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/pingcap/errors"
)
// SaveFileWithBackup will backup the file before save is.
// back meta.yaml as meta-2006-01-02T15:04:05Z07:00.yaml
// backup the files in the same dir of path if backupDir is empty.
func SaveFileWithBackup(path string, data []byte, backupDir string) error {
timestr := time.Now().Format(time.RFC3339Nano)
info, err := os.Stat(path)
if err != nil && !os.IsNotExist(err) {
return errors.AddStack(err)
}
if info != nil && info.IsDir() {
return errors.Errorf("%s is directory", path)
}
// backup file
if !os.IsNotExist(err) {
base := filepath.Base(path)
dir := filepath.Dir(path)
var backupName string
p := strings.Split(base, ".")
if len(p) == 1 {
backupName = base + "-" + timestr
} else {
backupName = strings.Join(p[0:len(p)-1], ".") + "-" + timestr + "." + p[len(p)-1]
}
backupData, err := ioutil.ReadFile(path)
if err != nil {
return errors.AddStack(err)
}
var backupPath string
if backupDir != "" {
backupPath = filepath.Join(backupDir, backupName)
} else {
backupPath = filepath.Join(dir, backupName)
}
err = ioutil.WriteFile(backupPath, backupData, 0644)
if err != nil {
return errors.AddStack(err)
}
}
err = ioutil.WriteFile(path, data, 0644)
if err != nil {
return errors.AddStack(err)
}
return nil
}