1package cache
2
3import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "os"
10 "path"
11 "sort"
12 "strconv"
13 "strings"
14
15 "github.com/MichaelMure/git-bug/bug"
16 "github.com/MichaelMure/git-bug/operations"
17 "github.com/MichaelMure/git-bug/repository"
18 "github.com/MichaelMure/git-bug/util/git"
19 "github.com/MichaelMure/git-bug/util/process"
20)
21
22const cacheFile = "cache"
23const formatVersion = 1
24
25type RepoCache struct {
26 // the underlying repo
27 repo repository.Repo
28 // excerpt of bugs data for all bugs
29 excerpts map[string]*BugExcerpt
30 // bug loaded in memory
31 bugs map[string]*BugCache
32}
33
34func NewRepoCache(r repository.Repo) (*RepoCache, error) {
35 c := &RepoCache{
36 repo: r,
37 bugs: make(map[string]*BugCache),
38 }
39
40 err := c.lock()
41 if err != nil {
42 return &RepoCache{}, err
43 }
44
45 err = c.load()
46 if err == nil {
47 return c, nil
48 }
49
50 c.buildCache()
51
52 return c, c.write()
53}
54
55// Repository return the underlying repository.
56// If you use this, make sure to never change the repo state.
57func (c *RepoCache) Repository() repository.Repo {
58 return c.repo
59}
60
61func (c *RepoCache) lock() error {
62 lockPath := repoLockFilePath(c.repo)
63
64 err := repoIsAvailable(c.repo)
65 if err != nil {
66 return err
67 }
68
69 f, err := os.Create(lockPath)
70 if err != nil {
71 return err
72 }
73
74 pid := fmt.Sprintf("%d", os.Getpid())
75 _, err = f.WriteString(pid)
76 if err != nil {
77 return err
78 }
79
80 return f.Close()
81}
82
83func (c *RepoCache) Close() error {
84 lockPath := repoLockFilePath(c.repo)
85 return os.Remove(lockPath)
86}
87
88// bugUpdated is a callback to trigger when the excerpt of a bug changed,
89// that is each time a bug is updated
90func (c *RepoCache) bugUpdated(id string) error {
91 b, ok := c.bugs[id]
92 if !ok {
93 panic("missing bug in the cache")
94 }
95
96 c.excerpts[id] = NewBugExcerpt(b.bug, b.Snapshot())
97
98 return c.write()
99}
100
101// load will try to read from the disk the bug cache file
102func (c *RepoCache) load() error {
103 f, err := os.Open(cacheFilePath(c.repo))
104 if err != nil {
105 return err
106 }
107
108 decoder := gob.NewDecoder(f)
109
110 aux := struct {
111 Version uint
112 Excerpts map[string]*BugExcerpt
113 }{}
114
115 err = decoder.Decode(&aux)
116 if err != nil {
117 return err
118 }
119
120 if aux.Version != 1 {
121 return fmt.Errorf("unknown cache format version %v", aux.Version)
122 }
123
124 c.excerpts = aux.Excerpts
125 return nil
126}
127
128// write will serialize on disk the bug cache file
129func (c *RepoCache) write() error {
130 var data bytes.Buffer
131
132 aux := struct {
133 Version uint
134 Excerpts map[string]*BugExcerpt
135 }{
136 Version: formatVersion,
137 Excerpts: c.excerpts,
138 }
139
140 encoder := gob.NewEncoder(&data)
141
142 err := encoder.Encode(aux)
143 if err != nil {
144 return err
145 }
146
147 f, err := os.Create(cacheFilePath(c.repo))
148 if err != nil {
149 return err
150 }
151
152 _, err = f.Write(data.Bytes())
153 if err != nil {
154 return err
155 }
156
157 return f.Close()
158}
159
160func cacheFilePath(repo repository.Repo) string {
161 return path.Join(repo.GetPath(), ".git", "git-bug", cacheFile)
162}
163
164func (c *RepoCache) buildCache() {
165 fmt.Printf("Building bug cache... ")
166
167 c.excerpts = make(map[string]*BugExcerpt)
168
169 allBugs := bug.ReadAllLocalBugs(c.repo)
170
171 for b := range allBugs {
172 snap := b.Bug.Compile()
173 c.excerpts[b.Bug.Id()] = NewBugExcerpt(b.Bug, &snap)
174 }
175
176 fmt.Println("Done.")
177}
178
179func (c *RepoCache) ResolveBug(id string) (*BugCache, error) {
180 cached, ok := c.bugs[id]
181 if ok {
182 return cached, nil
183 }
184
185 b, err := bug.ReadLocalBug(c.repo, id)
186 if err != nil {
187 return nil, err
188 }
189
190 cached = NewBugCache(c, b)
191 c.bugs[id] = cached
192
193 return cached, nil
194}
195
196func (c *RepoCache) ResolveBugPrefix(prefix string) (*BugCache, error) {
197 // preallocate but empty
198 matching := make([]string, 0, 5)
199
200 for id := range c.excerpts {
201 if strings.HasPrefix(id, prefix) {
202 matching = append(matching, id)
203 }
204 }
205
206 if len(matching) > 1 {
207 return nil, fmt.Errorf("Multiple matching bug found:\n%s", strings.Join(matching, "\n"))
208 }
209
210 return c.ResolveBug(matching[0])
211}
212
213func (c *RepoCache) QueryBugs(query *Query) []string {
214 if query == nil {
215 return c.AllBugsIds()
216 }
217
218 var filtered []*BugExcerpt
219
220 for _, excerpt := range c.excerpts {
221 if query.Match(excerpt) {
222 filtered = append(filtered, excerpt)
223 }
224 }
225
226 var sorter sort.Interface
227
228 switch query.OrderBy {
229 case OrderById:
230 sorter = BugsById(filtered)
231 case OrderByCreation:
232 sorter = BugsByCreationTime(filtered)
233 case OrderByEdit:
234 sorter = BugsByEditTime(filtered)
235 default:
236 panic("missing sort type")
237 }
238
239 if query.OrderDirection == OrderDescending {
240 sorter = sort.Reverse(sorter)
241 }
242
243 sort.Sort(sorter)
244
245 result := make([]string, len(filtered))
246
247 for i, val := range filtered {
248 result[i] = val.Id
249 }
250
251 return result
252}
253
254// AllBugsIds return all known bug ids
255func (c *RepoCache) AllBugsIds() []string {
256 result := make([]string, len(c.excerpts))
257
258 i := 0
259 for _, excerpt := range c.excerpts {
260 result[i] = excerpt.Id
261 i++
262 }
263
264 return result
265}
266
267// ClearAllBugs clear all bugs kept in memory
268func (c *RepoCache) ClearAllBugs() {
269 c.bugs = make(map[string]*BugCache)
270}
271
272// NewBug create a new bug
273// The new bug is written in the repository (commit)
274func (c *RepoCache) NewBug(title string, message string) (*BugCache, error) {
275 return c.NewBugWithFiles(title, message, nil)
276}
277
278// NewBugWithFiles create a new bug with attached files for the message
279// The new bug is written in the repository (commit)
280func (c *RepoCache) NewBugWithFiles(title string, message string, files []git.Hash) (*BugCache, error) {
281 author, err := bug.GetUser(c.repo)
282 if err != nil {
283 return nil, err
284 }
285
286 b, err := operations.CreateWithFiles(author, title, message, files)
287 if err != nil {
288 return nil, err
289 }
290
291 err = b.Commit(c.repo)
292 if err != nil {
293 return nil, err
294 }
295
296 cached := NewBugCache(c, b)
297 c.bugs[b.Id()] = cached
298
299 err = c.bugUpdated(b.Id())
300 if err != nil {
301 return nil, err
302 }
303
304 return cached, nil
305}
306
307// Fetch retrieve update from a remote
308// This does not change the local bugs state
309func (c *RepoCache) Fetch(remote string) (string, error) {
310 return bug.Fetch(c.repo, remote)
311}
312
313// MergeAll will merge all the available remote bug
314func (c *RepoCache) MergeAll(remote string) <-chan bug.MergeResult {
315 out := make(chan bug.MergeResult)
316
317 // Intercept merge results to update the cache properly
318 go func() {
319 defer close(out)
320
321 results := bug.MergeAll(c.repo, remote)
322 for result := range results {
323 if result.Err != nil {
324 continue
325 }
326
327 id := result.Id
328
329 switch result.Status {
330 case bug.MergeStatusNew, bug.MergeStatusUpdated:
331 b := result.Bug
332 snap := b.Compile()
333 c.excerpts[id] = NewBugExcerpt(b, &snap)
334
335 default:
336 }
337
338 out <- result
339 }
340
341 err := c.write()
342
343 // No easy way out here ..
344 if err != nil {
345 panic(err)
346 }
347 }()
348
349 return out
350}
351
352// Push update a remote with the local changes
353func (c *RepoCache) Push(remote string) (string, error) {
354 return bug.Push(c.repo, remote)
355}
356
357func repoLockFilePath(repo repository.Repo) string {
358 return path.Join(repo.GetPath(), ".git", "git-bug", lockfile)
359}
360
361// repoIsAvailable check is the given repository is locked by a Cache.
362// Note: this is a smart function that will cleanup the lock file if the
363// corresponding process is not there anymore.
364// If no error is returned, the repo is free to edit.
365func repoIsAvailable(repo repository.Repo) error {
366 lockPath := repoLockFilePath(repo)
367
368 // Todo: this leave way for a racey access to the repo between the test
369 // if the file exist and the actual write. It's probably not a problem in
370 // practice because using a repository will be done from user interaction
371 // or in a context where a single instance of git-bug is already guaranteed
372 // (say, a server with the web UI running). But still, that might be nice to
373 // have a mutex or something to guard that.
374
375 // Todo: this will fail if somehow the filesystem is shared with another
376 // computer. Should add a configuration that prevent the cleaning of the
377 // lock file
378
379 f, err := os.Open(lockPath)
380
381 if err != nil && !os.IsNotExist(err) {
382 return err
383 }
384
385 if err == nil {
386 // lock file already exist
387 buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
388 if err != nil {
389 return err
390 }
391 if len(buf) == 10 {
392 return fmt.Errorf("the lock file should be < 10 bytes")
393 }
394
395 pid, err := strconv.Atoi(string(buf))
396 if err != nil {
397 return err
398 }
399
400 if process.IsRunning(pid) {
401 return fmt.Errorf("the repository you want to access is already locked by the process pid %d", pid)
402 }
403
404 // The lock file is just laying there after a crash, clean it
405
406 fmt.Println("A lock file is present but the corresponding process is not, removing it.")
407 err = f.Close()
408 if err != nil {
409 return err
410 }
411
412 os.Remove(lockPath)
413 if err != nil {
414 return err
415 }
416 }
417
418 return nil
419}