-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
151 lines (129 loc) · 2.38 KB
/
store.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
package store
import (
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
)
var (
dir string
mtx sync.RWMutex
repos map[string]archives
)
type archives map[string]string
func init() {
var home string
if runtime.GOOS == "windows" {
home = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
} else {
home = os.Getenv("HOME")
}
_, err := Dir(filepath.Join(home, ".gopkg"))
if err != nil {
log.Fatal(err)
}
}
func walk(dir string) (repos map[string]archives, err error) {
repos = make(map[string]archives)
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return err
}
rel, err := filepath.Rel(dir, path)
if err != nil {
return err
}
base := filepath.Base(rel)
ss := strings.Split(base, ".")
if len(ss) != 2 {
return nil
}
sha := ss[0]
ext := "." + ss[1]
repo := filepath.Dir(rel)
archives, ok := repos[repo]
if !ok {
archives = make(map[string]string)
repos[repo] = archives
}
archives[sha] = ext
return nil
})
return
}
func Dir(path string) (string, error) {
if path != "" && dir != path {
os.MkdirAll(path, os.ModePerm)
r, err := walk(path)
if err != nil {
return "", err
}
mtx.Lock()
repos = r
dir = path
mtx.Unlock()
}
return dir, nil
}
func Map(f func(repo, sha, ext string) error) (err error) {
mtx.RLock()
defer mtx.RUnlock()
for repo, archives := range repos {
for sha, ext := range archives {
err = f(repo, sha, ext)
if err != nil {
return
}
}
}
return
}
func Get(repo, sha string) (path string, ok bool) {
mtx.RLock()
defer mtx.RUnlock()
archives, ok := repos[repo]
if !ok {
return
}
ext, ok := archives[sha]
if !ok {
return
}
path = filepath.Join(dir, repo, sha) + ext
return
}
func Put(repo, sha, ext string, r io.Reader) (err error) {
path := filepath.Join(dir, repo)
os.MkdirAll(path, os.ModePerm)
prefix := sha + ext + "."
f, err := ioutil.TempFile(path, prefix)
if err != nil {
return
}
defer f.Close()
_, err = io.Copy(f, r)
if err != nil {
return
}
path = filepath.Join(dir, repo, sha+ext)
err = os.Rename(f.Name(), path)
if err != nil {
return
}
mtx.Lock()
archives, ok := repos[repo]
if !ok {
archives = make(map[string]string)
repos[repo] = archives
}
archives[sha] = ext
mtx.Unlock()
return
}