/
index.go
258 lines (218 loc) · 5.48 KB
/
index.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package fs
import (
"crypto/sha1"
"fmt"
"hash"
"os"
"path/filepath"
"strings"
)
// Represent a weak checksum as described in the rsync algorithm paper
type WeakChecksum struct {
a int
b int
}
// Reset the state of the checksum
func (weak *WeakChecksum) Reset() {
weak.a = 0
weak.b = 0
}
// Write a block of data into the checksum
func (weak *WeakChecksum) Write(buf []byte) {
for i := 0; i < len(buf); i++ {
b := int(buf[i])
weak.a += b
weak.b += (len(buf) - i) * b
}
}
// Get the current weak checksum value
func (weak *WeakChecksum) Get() int {
return weak.b<<16 | weak.a
}
// Roll the checksum forward by one byte
func (weak *WeakChecksum) Roll(removedByte byte, newByte byte) {
weak.a -= int(removedByte) - int(newByte)
weak.b -= int(removedByte)*BLOCKSIZE - weak.a
}
type IndexFilter func(path string, f *os.FileInfo) bool
func AlwaysMatch(path string, f *os.FileInfo) bool { return true }
func AllMatch(filters ...IndexFilter) IndexFilter {
return func(path string, f *os.FileInfo) bool {
for _, fn := range filters {
if !fn(path, f) {
return false
}
}
return true
}
}
func AnyMatch(filters ...IndexFilter) IndexFilter {
return func(path string, f *os.FileInfo) bool {
for _, fn := range filters {
if fn(path, f) {
return true
}
}
return false
}
}
type Indexer struct {
Path string
Repo NodeRepo
Filter IndexFilter
Errors chan<- os.Error
root Dir
dirMap map[string]Dir
}
// Initialize the Indexer for filepath.Walk visit
func (indexer *Indexer) initWalk() {
indexer.Path = filepath.Clean(indexer.Path)
indexer.Path = strings.TrimRight(indexer.Path, "/\\")
if indexer.Filter == nil {
indexer.Filter = AlwaysMatch
}
indexer.root = nil
indexer.dirMap = make(map[string]Dir)
if rootInfo, err := os.Stat(indexer.Path); err == nil {
indexer.VisitDir(indexer.Path, rootInfo)
indexer.root = indexer.dirMap[indexer.Path]
}
}
// Indexer callback for directories
func (indexer *Indexer) VisitDir(path string, f *os.FileInfo) bool {
if !indexer.Filter(path, f) {
return false
}
path = filepath.Clean(path)
dir, hasDir := indexer.dirMap[path]
if !hasDir {
dirname, basename := filepath.Split(path)
dirname = strings.TrimRight(dirname, "/\\") // remove the trailing slash
parentDir, hasParent := indexer.dirMap[dirname]
info := &DirInfo{
Name: basename,
Mode: f.Mode}
if hasParent {
info.Parent = parentDir.Info().Strong
dir = indexer.Repo.AddDir(parentDir, info)
} else {
info.Name = ""
dir = indexer.Repo.AddDir(nil, info)
}
indexer.dirMap[path] = dir
}
return true
}
// IndexDir visitor callback for files
func (indexer *Indexer) VisitFile(path string, f *os.FileInfo) {
if !indexer.Filter(path, f) {
return
}
fileInfo, blocksInfo, err := IndexFile(path)
if err == nil {
dirpath, _ := filepath.Split(path)
dirpath = filepath.Clean(dirpath)
if dirinfo, err := os.Stat(dirpath); err == nil {
indexer.VisitDir(dirpath, dirinfo)
if fileParent, hasParent := indexer.dirMap[dirpath]; hasParent {
indexer.Repo.AddFile(fileParent, fileInfo, blocksInfo)
return
} else if indexer.Errors != nil {
indexer.Errors <- os.NewError("cannot locate parent directory")
}
}
} else if indexer.Errors != nil {
indexer.Errors <- err
}
}
func IndexDir(path string, repo NodeRepo) (Dir, []os.Error) {
errors := []os.Error{}
dirChan := make(chan Dir, 1)
errorChan := make(chan os.Error, 1)
indexer := &Indexer{Path: path, Repo: repo, Errors: errorChan}
go func() {
dirChan <- indexer.Index()
close(errorChan)
}()
for error := range errorChan {
errors = append(errors, error)
}
dir := <-dirChan
return dir, errors
}
func (indexer *Indexer) Index() Dir {
control := make(chan bool)
indexer.initWalk()
go func() {
filepath.Walk(indexer.Path, indexer, indexer.Errors)
close(control)
}()
<-control
if indexer.root != nil {
indexer.root.UpdateStrong()
}
return indexer.root
}
// Build a hierarchical tree model representing a file's contents
func IndexFile(path string) (fileInfo *FileInfo, blocksInfo []*BlockInfo, err os.Error) {
var f *os.File
var buf [BLOCKSIZE]byte
stat, err := os.Stat(path)
if stat == nil {
return nil, nil, err
} else if !stat.IsRegular() {
return nil, nil, os.NewError(fmt.Sprintf("%s: not a regular file", path))
}
f, err = os.Open(path)
if f == nil {
return nil, nil, err
}
defer f.Close()
_, basename := filepath.Split(path)
fileInfo = &FileInfo{
Name: basename,
Mode: stat.Mode,
Size: stat.Size}
var block *BlockInfo
sha1 := sha1.New()
blockNum := 0
blocksInfo = []*BlockInfo{}
for {
switch rd, err := f.Read(buf[:]); true {
case rd < 0:
return nil, nil, err
case rd == 0:
fileInfo.Strong = toHexString(sha1)
return fileInfo, blocksInfo, nil
case rd > 0:
// Update block hashes
block = IndexBlock(buf[0:rd])
block.Position = blockNum
blocksInfo = append(blocksInfo, block)
// update file hash
sha1.Write(buf[0:rd])
// Increment block counter
blockNum++
}
}
panic("Impossible")
}
// Render a Hash as a hexadecimal string.
func toHexString(hash hash.Hash) string {
return fmt.Sprintf("%x", hash.Sum())
}
// Strong checksum algorithm used throughout replican
// For now, it's SHA-1.
func StrongChecksum(buf []byte) string {
var sha1 = sha1.New()
sha1.Write(buf)
return toHexString(sha1)
}
// Model a block with weak and strong checksums.
func IndexBlock(buf []byte) *BlockInfo {
var weak = new(WeakChecksum)
weak.Write(buf)
return &BlockInfo{
Weak: weak.Get(),
Strong: StrongChecksum(buf)}
}