-
Notifications
You must be signed in to change notification settings - Fork 0
/
store_list.go
100 lines (78 loc) · 2.05 KB
/
store_list.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
package main
import (
"fmt"
"path/filepath"
)
type storeList struct {
storeListFile jsonFile
storeMap map[string]*store
}
type storeListEntry struct {
Name string
Root string
}
const storeListFileName = "storelist"
func loadStoreList(path string) (storeList, error) {
storeListFilePath := fmt.Sprintf("%s/%s", path, storeListFileName)
storeListFile, err := newJsonFile(storeListFilePath)
if err != nil {
return storeList{}, err
}
storeMap := make(map[string]*store)
sl := storeList{
storeListFile: storeListFile,
storeMap: storeMap,
}
var storeListEntries []storeListEntry
if err := sl.storeListFile.read(&storeListEntries); err != nil {
return storeList{}, fmt.Errorf("reading store list file: %v", err)
}
for _, entry := range storeListEntries {
store, err := openStore(entry.Root)
if err != nil {
return storeList{}, fmt.Errorf("opening store %q: %v", entry.Name, err)
}
storeMap[entry.Name] = &store
}
return sl, nil
}
func (sl storeList) stores() map[string]*store {
return sl.storeMap
}
func (sl storeList) addStore(name string, storePath string) error {
if name == "" {
_, name = filepath.Split(storePath)
}
store, err := openStore(storePath)
if err != nil {
return fmt.Errorf("opening store %q: %v", storePath, err)
}
if retrievedStore, ok := (sl.storeMap)[name]; ok {
if retrievedStore.rootPath == store.rootPath {
return nil
}
return storeNameExistError(name)
}
(sl.storeMap)[name] = &store
if err := sl.persist(); err != nil {
return fmt.Errorf("persisting store list: %v", err)
}
return nil
}
func (sl storeList) persist() error {
var storeListEntries []storeListEntry
for name, store := range sl.storeMap {
storeListEntries = append(storeListEntries, storeListEntry{
Name: name,
Root: store.rootPath,
})
}
if err := sl.storeListFile.write(&storeListEntries); err != nil {
return fmt.Errorf("writing store file: %v", err)
}
return nil
}
type storeNameExistError string
func (e storeNameExistError) Error() string {
return fmt.Sprintf("store %q already exists", string(e))
}