-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeta.go
113 lines (96 loc) · 2.03 KB
/
meta.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
package iodb
import (
"encoding/json"
"math/big"
"os"
"path/filepath"
)
var one = big.NewInt(1)
type metadata struct {
Counter *big.Int `json:"counter"`
ExpiryDate map[string]int64 `json:"expiryDate,omitempty"`
Extra map[string]map[string]string `json:"extra,omitempty"`
path string
}
func (m *metadata) incCounter() *big.Int {
return m.Counter.Add(m.Counter, one)
}
func (m *metadata) SetExpiryDate(path string, ts int64) {
if ts == 0 && m.ExpiryDate != nil {
delete(m.ExpiryDate, path)
if len(m.ExpiryDate) == 0 {
m.ExpiryDate = nil
}
} else {
if m.ExpiryDate == nil {
m.ExpiryDate = map[string]int64{}
}
m.ExpiryDate[path] = ts
}
}
func (m *metadata) SetExtraData(path string, key string, val string) {
if m.Extra == nil {
if val == "" {
return
}
m.Extra = make(map[string]map[string]string)
}
mm := m.Extra[path]
if mm == nil {
if val == "" {
return
}
mm = map[string]string{}
m.Extra[path] = mm
}
if val == "" {
delete(mm, key)
if len(mm) == 0 {
delete(m.Extra, path)
}
} else {
mm[key] = val
}
}
func (m *metadata) CopyExtra(path string) (out map[string]string) {
mm := m.Extra[path]
out = make(map[string]string, len(mm))
for k, v := range mm {
out[k] = v
}
return
}
func (m *metadata) store() (err error) {
var f *os.File
tmpPath := m.path + ".tmp"
if f, err = os.Create(tmpPath); err != nil {
return err
}
if err = json.NewEncoder(f).Encode(m); err != nil {
f.Close() // can't defer it because we wanna close it before the rename :|
return err
}
if err = f.Close(); err != nil {
return
}
return os.Rename(tmpPath, m.path)
}
func loadMetadata(p string) (*metadata, error) {
p = filepath.Join(p, ".meta")
m := &metadata{Counter: big.NewInt(0), path: p}
f, err := os.Open(p)
if err != nil {
if os.IsNotExist(err) {
return m, nil
}
return nil, err
}
if err = json.NewDecoder(f).Decode(m); err != nil {
f.Close()
return nil, err
}
if err = f.Close(); err != nil {
return nil, err
}
return m, nil
}