-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile.go
76 lines (64 loc) · 1.31 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
package main
import (
"bufio"
"container/list"
"fmt"
"github.com/libercv/peerbackup/hasher"
"io"
"os"
"path"
"path/filepath"
)
type FileMetadata struct {
FileInfo os.FileInfo
Path string
CryptHash []byte
AdlerHash uint32
// List of hash fragments
Fragments list.List
}
type FileBlock struct {
CryptHash []byte
AdlerHash uint32
}
func GetFileInfo(fileName string) *FileMetadata {
m := new(FileMetadata)
fi, _ := os.Stat(fileName)
m.FileInfo = fi
m.Path = filepath.Dir(fileName)
// Inefficient way of calculating the hashes
// Multiwriter should be better.
if !fi.IsDir() {
m.CryptHash = hasher.GetFileSHA256(fileName)
m.AdlerHash = hasher.GetFileAdler32(fileName)
}
// Again, use multiwriter, not parse thrice every file...
block := new(FileBlock)
m.Fragments.PushBack(block)
return m
}
func (fm *FileMetadata) BackupFile(dstFolder string) {
name := path.Join(fm.Path, fm.FileInfo.Name())
fi, err := os.Open(name)
if err != nil {
panic(err)
}
defer func() {
if err := fi.Close(); err != nil {
panic(err)
}
}()
r := bufio.NewReader(fi)
buf := make([]byte, 262144)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
hash := hasher.GetSHA256(buf)
WriteFileGZIP(path.Join(dstFolder, fmt.Sprintf("%x", hash)), buf)
}
}