-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
105 lines (87 loc) · 1.95 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
93
94
95
96
97
98
99
100
101
102
103
104
105
package watcher
import (
"bytes"
"crypto/sha256"
"io/ioutil"
"sync"
"github.com/dnjp/zync/proto/zync/v1"
)
// CID represents an IPFS content identifier. See https://docs.ipfs.io/concepts/content-addressing/
type CID string
func (cid CID) String() string {
return string(cid)
}
// FilePath represents a proper file path
type FilePath string
func (path FilePath) String() string {
return string(path)
}
// File represents a file being watched
type File struct {
CID CID `json:"cid"`
AbsolutePath FilePath `json:"absolute_path"`
Watcher *Watcher `json:"-"`
checksum [32]byte
data *bytes.Buffer
mux sync.RWMutex
}
// NewFile constructs a File, updating its properties from disk
func NewFile(path FilePath) (*File, error) {
f := &File{
AbsolutePath: path,
data: new(bytes.Buffer),
}
_, err := f.Read()
if err != nil {
return nil, err
}
return f, nil
}
// AssignCID updates the CID reference in the File
func (f *File) AssignCID(cid CID) {
f.mux.Lock()
f.CID = cid
f.mux.Unlock()
}
// Read reads the contents of the file, updating its current checksum
func (f *File) Read() ([]byte, error) {
b, err := ioutil.ReadFile(f.AbsolutePath.String())
if err != nil {
return nil, err
}
f.mux.Lock()
f.checksum = sha256.Sum256(b)
f.data.Reset()
_, err = f.data.Write(b)
if err != nil {
f.mux.Unlock()
return nil, err
}
f.mux.Unlock()
return b, nil
}
// Checksum prepares a SHA256 checksum of the file contents
func (f *File) Checksum() ([32]byte, error) {
b, err := f.Read()
if err != nil {
return [32]byte{}, err
}
return sha256.Sum256(b), nil
}
// Status returns the RPC format for the File
func (f *File) Status() *zync.File {
return &zync.File{
Cid: f.CID.String(),
AbsolutePath: f.AbsolutePath.String(),
}
}
func (f *File) attachWatcher(w *Watcher) {
f.mux.Lock()
f.Watcher = w
f.mux.Unlock()
}
func (f *File) detachWatcher() {
f.mux.Lock()
f.Watcher = nil
f.mux.Unlock()
}