-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.go
58 lines (45 loc) · 1.02 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
// Copyright 2016 David Lavieri. All rights reserved.
// Use of this source code is governed by a MIT License
// License that can be found in the LICENSE file.
package main
import (
"bufio"
"errors"
"io"
"os"
"strings"
)
func createBackup(path, suffix string, overwrite bool) (string, error) {
f, err := os.Open(path)
defer f.Close()
if err != nil {
return "", err
}
name := f.Name()
outputName := name[:strings.Index(name, ".tpl")] + suffix + ".tpl"
_, err = os.Stat(outputName)
if !os.IsNotExist(err) && !overwrite {
return "", errors.New("Backup file already exist")
}
outputFile, err := os.Create(outputName)
if err != nil {
return "", err
}
defer outputFile.Close()
reader := bufio.NewReaderSize(f, 1024)
writer := bufio.NewWriterSize(outputFile, 1024)
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return "", err
}
_, err = writer.WriteString(line)
if err != nil {
return "", err
}
}
writer.Flush()
return outputName, nil
}