forked from sajari/storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.go
102 lines (88 loc) · 2.08 KB
/
hash.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
package storage
import (
"bytes"
"errors"
"fmt"
"hash"
"io"
"golang.org/x/net/context"
)
// HashFS creates a content addressable filesystem using hash.Hash
// to sum the content and store it using that name.
func HashFS(h hash.Hash, fs FS, gs GetSetter) FS {
return &hashFS{
h: h,
fs: fs,
gs: gs,
}
}
type hashFS struct {
h hash.Hash
fs FS
gs GetSetter
}
// GetSetter implements a key-value store which is concurrency safe (can
// be used in multiple go-routines concurrently).
type GetSetter interface {
Get(key string) (string, error)
Set(key string, value string) error
Delete(key string) error
}
// Open implements FS.
func (hfs hashFS) Open(ctx context.Context, path string) (*File, error) {
v, err := hfs.gs.Get(path)
if err != nil {
return nil, err
}
return hfs.fs.Open(ctx, v)
}
// Walk implements Walker.
func (hfs hashFS) Walk(ctx context.Context, path string, fn WalkFn) error {
return errors.New("HashFS.Walk is not implemented")
}
type hashWriteCloser struct {
buf *bytes.Buffer
path string
ctx context.Context
hfs hashFS
}
func (w *hashWriteCloser) Write(b []byte) (int, error) {
n, err := w.buf.Write(b)
if err != nil {
return n, err
}
w.hfs.h.Write(b) // never returns an error
return n, nil
}
func (w *hashWriteCloser) Close() error {
hashPath := fmt.Sprintf("%x", w.hfs.h.Sum(nil))
if err := w.hfs.gs.Set(w.path, hashPath); err != nil {
return err
}
fsw, err := w.hfs.fs.Create(w.ctx, hashPath)
if err != nil {
return err
}
if _, err := io.Copy(fsw, w.buf); err != nil {
return err
}
return fsw.Close()
}
// TODO(trent): make sure that you document the FS.Create method
// to Close it, and check the error. If err != nil then the file might not have
// been written.
func (hfs hashFS) Create(ctx context.Context, path string) (io.WriteCloser, error) {
return &hashWriteCloser{
buf: &bytes.Buffer{},
path: path,
ctx: ctx,
hfs: hfs,
}, nil
}
// Delete implements FS.
func (hfs hashFS) Delete(ctx context.Context, path string) error {
if err := hfs.fs.Delete(ctx, path); err != nil {
return err
}
return hfs.gs.Delete(path)
}