-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
92 lines (75 loc) · 1.91 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
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
package file
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"github.com/miracl/casper"
"github.com/pkg/errors"
"github.com/sergi/go-diff/diffmatchpatch"
)
// Storage is an implementation of the storage interface that stores in file.
// This implementation is mostly for testing.
type Storage struct {
path string
}
// New returns new file storage.
func New(path string) *Storage {
return &Storage{path: path}
}
func (s Storage) String(format string) (string, error) {
data, err := ioutil.ReadFile(s.path)
if err != nil {
return "", errors.Wrapf(err, "reading file %v failed", s.path)
}
return string(data), nil
}
// GetChanges returns changes between the config and the Storage content.
func (s Storage) GetChanges(config []byte, format, key string) (casper.Changes, error) {
data, err := ioutil.ReadFile(s.path)
if err != nil {
return nil, errors.Wrapf(err, "reading file %v failed", s.path)
}
if bytes.Compare(data, config) == 0 {
return &changes{}, nil
}
return &changes{data, config}, nil
}
// Diff returns the visual representation of the changes.
func (s Storage) Diff(cs casper.Changes, pretty bool) string {
if cs.Len() == 0 {
return ""
}
c := cs.(*changes)
if pretty {
dmp := diffmatchpatch.New()
return dmp.DiffPrettyText(dmp.DiffMain(string(c.old), string(c.new), false))
}
return fmt.Sprintf("-%v\n+%v", string(c.old), string(c.new))
}
// Push changes to the storage.
func (s Storage) Push(cs casper.Changes) error {
c := cs.(*changes)
f, err := os.OpenFile(s.path, os.O_WRONLY, 0777)
if err != nil {
return errors.Wrapf(err, "opening file %v failed", s.path)
}
defer f.Close()
w := bufio.NewWriter(f)
if _, err := w.Write(c.new); err != nil {
return errors.Wrapf(err, "writing to file %v failed", s.path)
}
w.Flush()
return nil
}
type changes struct {
old []byte
new []byte
}
func (c changes) Len() int {
if len(c.old) == 0 && len(c.new) == 0 {
return 0
}
return 1
}