-
Notifications
You must be signed in to change notification settings - Fork 0
/
bufferedfilesystem.go
110 lines (97 loc) · 1.95 KB
/
bufferedfilesystem.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
package fs
import (
"bytes"
"crypto/sha1"
"io"
"os"
"path/filepath"
)
func hashFile(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
hasher := sha1.New()
_, err = io.Copy(hasher, f)
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
func fileHaveSameContent(path1 string, path2 string) bool {
// Check size, first.
i1, err := os.Stat(path1)
if err != nil {
return false
}
i2, err := os.Stat(path1)
if err != nil {
return false
}
if i1.Size() != i2.Size() {
return false
}
// Check contents.
h1, err := hashFile(path1)
if err != nil {
return false
}
h2, err := hashFile(path2)
if err != nil {
return false
}
return bytes.Equal(h1, h2)
}
func moveFile(src string, dst string) error {
dir := filepath.Dir(dst)
err := os.MkdirAll(dir, 0755)
if err != nil {
return err
}
// TODO copy and remove src if rename fails.
return os.Rename(src, dst)
}
type fileOutput struct {
Tmp string
Dst string
Perm os.FileMode
}
type bufferedFileSystem struct {
files []fileOutput
temp *TempDir
}
func (o *bufferedFileSystem) InputFile(path string) DataInput {
return &DataFile{Path: path}
}
func (o *bufferedFileSystem) OutputFile(path string, perm os.FileMode) DataOutput {
temp_file, err := o.temp.TempFile("out_")
if err != nil {
return nil
}
name := temp_file.Name()
o.files = append(o.files, fileOutput{Tmp: name, Dst: path, Perm: perm})
return &DataFile{Path: name}
}
func (o *bufferedFileSystem) TempFile() Data {
return &DataBuffer{}
}
func (o *bufferedFileSystem) Commit() error {
for _, fout := range o.files {
if !fileHaveSameContent(fout.Tmp, fout.Dst) {
err := moveFile(fout.Tmp, fout.Dst)
if err != nil {
return err
}
}
err := os.Chmod(fout.Dst, fout.Perm)
if err != nil {
return err
}
}
o.files = nil
return nil
}
func MakeBufferedFileSystem(temp *TempDir) BufferedFileSystem {
return &bufferedFileSystem{temp: temp}
}