1package cache
2
3import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "os"
10 "path"
11 "strconv"
12 "strings"
13
14 "github.com/MichaelMure/git-bug/bug"
15 "github.com/MichaelMure/git-bug/bug/operations"
16 "github.com/MichaelMure/git-bug/repository"
17 "github.com/MichaelMure/git-bug/util"
18)
19
20type RepoCache struct {
21 repo repository.Repo
22 excerpts map[string]BugExcerpt
23 bugs map[string]*BugCache
24}
25
26func NewRepoCache(r repository.Repo) (*RepoCache, error) {
27 c := &RepoCache{
28 repo: r,
29 bugs: make(map[string]*BugCache),
30 }
31
32 err := c.lock()
33 if err != nil {
34 return &RepoCache{}, err
35 }
36
37 err = c.loadExcerpts()
38 if err == nil {
39 return c, nil
40 }
41
42 c.buildAllExcerpt()
43
44 return c, c.writeExcerpts()
45}
46
47func (c *RepoCache) Repository() repository.Repo {
48 return c.repo
49}
50
51func (c *RepoCache) lock() error {
52 lockPath := repoLockFilePath(c.repo)
53
54 err := repoIsAvailable(c.repo)
55 if err != nil {
56 return err
57 }
58
59 f, err := os.Create(lockPath)
60 if err != nil {
61 return err
62 }
63
64 pid := fmt.Sprintf("%d", os.Getpid())
65 _, err = f.WriteString(pid)
66 if err != nil {
67 return err
68 }
69
70 return f.Close()
71}
72
73func (c *RepoCache) Close() error {
74 lockPath := repoLockFilePath(c.repo)
75 return os.Remove(lockPath)
76}
77
78// bugUpdated is a callback to trigger when the excerpt of a bug changed,
79// that is each time a bug is updated
80func (c *RepoCache) bugUpdated(id string) error {
81 b, ok := c.bugs[id]
82 if !ok {
83 panic("missing bug in the cache")
84 }
85
86 c.excerpts[id] = NewBugExcerpt(b.bug, b.Snapshot())
87
88 return c.writeExcerpts()
89}
90
91// loadExcerpts will try to read from the disk the bug excerpt file
92func (c *RepoCache) loadExcerpts() error {
93 excerptsPath := repoExcerptsFilePath(c.repo)
94
95 f, err := os.Open(excerptsPath)
96 if err != nil {
97 return err
98 }
99
100 decoder := gob.NewDecoder(f)
101
102 var excerpts map[string]BugExcerpt
103
104 err = decoder.Decode(&excerpts)
105 if err != nil {
106 return err
107 }
108
109 c.excerpts = excerpts
110 return nil
111}
112
113// writeExcerpts will serialize on disk the BugExcerpt array
114func (c *RepoCache) writeExcerpts() error {
115 var data bytes.Buffer
116
117 encoder := gob.NewEncoder(&data)
118
119 err := encoder.Encode(c.excerpts)
120 if err != nil {
121 return err
122 }
123
124 excerptsPath := repoExcerptsFilePath(c.repo)
125
126 f, err := os.Create(excerptsPath)
127 if err != nil {
128 return err
129 }
130
131 _, err = f.Write(data.Bytes())
132 if err != nil {
133 return err
134 }
135
136 return f.Close()
137}
138
139func repoExcerptsFilePath(repo repository.Repo) string {
140 return path.Join(repo.GetPath(), ".git", "git-bug", excerptsFile)
141}
142
143func (c *RepoCache) buildAllExcerpt() {
144 c.excerpts = make(map[string]BugExcerpt)
145
146 allBugs := bug.ReadAllLocalBugs(c.repo)
147
148 for b := range allBugs {
149 snap := b.Bug.Compile()
150 c.excerpts[b.Bug.Id()] = NewBugExcerpt(b.Bug, &snap)
151 }
152}
153
154func (c *RepoCache) ResolveBug(id string) (*BugCache, error) {
155 cached, ok := c.bugs[id]
156 if ok {
157 return cached, nil
158 }
159
160 b, err := bug.ReadLocalBug(c.repo, id)
161 if err != nil {
162 return nil, err
163 }
164
165 cached = NewBugCache(c, b)
166 c.bugs[id] = cached
167
168 return cached, nil
169}
170
171func (c *RepoCache) ResolveBugPrefix(prefix string) (*BugCache, error) {
172 // preallocate but empty
173 matching := make([]string, 0, 5)
174
175 for id := range c.bugs {
176 if strings.HasPrefix(id, prefix) {
177 matching = append(matching, id)
178 }
179 }
180
181 // TODO: should check matching bug in the repo as well
182
183 if len(matching) > 1 {
184 return nil, fmt.Errorf("Multiple matching bug found:\n%s", strings.Join(matching, "\n"))
185 }
186
187 if len(matching) == 1 {
188 b := c.bugs[matching[0]]
189 return b, nil
190 }
191
192 b, err := bug.FindLocalBug(c.repo, prefix)
193
194 if err != nil {
195 return nil, err
196 }
197
198 cached := NewBugCache(c, b)
199 c.bugs[b.Id()] = cached
200
201 return cached, nil
202}
203
204func (c *RepoCache) AllBugIds() ([]string, error) {
205 return bug.ListLocalIds(c.repo)
206}
207
208func (c *RepoCache) ClearAllBugs() {
209 c.bugs = make(map[string]*BugCache)
210}
211
212func (c *RepoCache) NewBug(title string, message string) (*BugCache, error) {
213 return c.NewBugWithFiles(title, message, nil)
214}
215
216func (c *RepoCache) NewBugWithFiles(title string, message string, files []util.Hash) (*BugCache, error) {
217 author, err := bug.GetUser(c.repo)
218 if err != nil {
219 return nil, err
220 }
221
222 b, err := operations.CreateWithFiles(author, title, message, files)
223 if err != nil {
224 return nil, err
225 }
226
227 err = b.Commit(c.repo)
228 if err != nil {
229 return nil, err
230 }
231
232 cached := NewBugCache(c, b)
233 c.bugs[b.Id()] = cached
234
235 return cached, nil
236}
237
238func (c *RepoCache) Fetch(remote string) (string, error) {
239 return bug.Fetch(c.repo, remote)
240}
241
242func (c *RepoCache) MergeAll(remote string) <-chan bug.MergeResult {
243 return bug.MergeAll(c.repo, remote)
244}
245
246func (c *RepoCache) Pull(remote string, out io.Writer) error {
247 return bug.Pull(c.repo, out, remote)
248}
249
250func (c *RepoCache) Push(remote string) (string, error) {
251 return bug.Push(c.repo, remote)
252}
253
254func repoLockFilePath(repo repository.Repo) string {
255 return path.Join(repo.GetPath(), ".git", "git-bug", lockfile)
256}
257
258// repoIsAvailable check is the given repository is locked by a Cache.
259// Note: this is a smart function that will cleanup the lock file if the
260// corresponding process is not there anymore.
261// If no error is returned, the repo is free to edit.
262// @Deprecated
263func repoIsAvailable(repo repository.Repo) error {
264 lockPath := repoLockFilePath(repo)
265
266 // Todo: this leave way for a racey access to the repo between the test
267 // if the file exist and the actual write. It's probably not a problem in
268 // practice because using a repository will be done from user interaction
269 // or in a context where a single instance of git-bug is already guaranteed
270 // (say, a server with the web UI running). But still, that might be nice to
271 // have a mutex or something to guard that.
272
273 // Todo: this will fail if somehow the filesystem is shared with another
274 // computer. Should add a configuration that prevent the cleaning of the
275 // lock file
276
277 f, err := os.Open(lockPath)
278
279 if err != nil && !os.IsNotExist(err) {
280 return err
281 }
282
283 if err == nil {
284 // lock file already exist
285 buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
286 if err != nil {
287 return err
288 }
289 if len(buf) == 10 {
290 return fmt.Errorf("The lock file should be < 10 bytes")
291 }
292
293 pid, err := strconv.Atoi(string(buf))
294 if err != nil {
295 return err
296 }
297
298 if util.ProcessIsRunning(pid) {
299 return fmt.Errorf("The repository you want to access is already locked by the process pid %d", pid)
300 }
301
302 // The lock file is just laying there after a crash, clean it
303
304 fmt.Println("A lock file is present but the corresponding process is not, removing it.")
305 err = f.Close()
306 if err != nil {
307 return err
308 }
309
310 os.Remove(lockPath)
311 if err != nil {
312 return err
313 }
314 }
315
316 return nil
317}