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
47// Repository return the underlying repository.
48// If you use this, make sure to never change the repo state.
49func (c *RepoCache) Repository() repository.Repo {
50 return c.repo
51}
52
53func (c *RepoCache) lock() error {
54 lockPath := repoLockFilePath(c.repo)
55
56 err := repoIsAvailable(c.repo)
57 if err != nil {
58 return err
59 }
60
61 f, err := os.Create(lockPath)
62 if err != nil {
63 return err
64 }
65
66 pid := fmt.Sprintf("%d", os.Getpid())
67 _, err = f.WriteString(pid)
68 if err != nil {
69 return err
70 }
71
72 return f.Close()
73}
74
75func (c *RepoCache) Close() error {
76 lockPath := repoLockFilePath(c.repo)
77 return os.Remove(lockPath)
78}
79
80// bugUpdated is a callback to trigger when the excerpt of a bug changed,
81// that is each time a bug is updated
82func (c *RepoCache) bugUpdated(id string) error {
83 b, ok := c.bugs[id]
84 if !ok {
85 panic("missing bug in the cache")
86 }
87
88 c.excerpts[id] = NewBugExcerpt(b.bug, b.Snapshot())
89
90 return c.writeExcerpts()
91}
92
93// loadExcerpts will try to read from the disk the bug excerpt file
94func (c *RepoCache) loadExcerpts() error {
95 excerptsPath := repoExcerptsFilePath(c.repo)
96
97 f, err := os.Open(excerptsPath)
98 if err != nil {
99 return err
100 }
101
102 decoder := gob.NewDecoder(f)
103
104 var excerpts map[string]BugExcerpt
105
106 err = decoder.Decode(&excerpts)
107 if err != nil {
108 return err
109 }
110
111 c.excerpts = excerpts
112 return nil
113}
114
115// writeExcerpts will serialize on disk the BugExcerpt array
116func (c *RepoCache) writeExcerpts() error {
117 var data bytes.Buffer
118
119 encoder := gob.NewEncoder(&data)
120
121 err := encoder.Encode(c.excerpts)
122 if err != nil {
123 return err
124 }
125
126 excerptsPath := repoExcerptsFilePath(c.repo)
127
128 f, err := os.Create(excerptsPath)
129 if err != nil {
130 return err
131 }
132
133 _, err = f.Write(data.Bytes())
134 if err != nil {
135 return err
136 }
137
138 return f.Close()
139}
140
141func repoExcerptsFilePath(repo repository.Repo) string {
142 return path.Join(repo.GetPath(), ".git", "git-bug", excerptsFile)
143}
144
145func (c *RepoCache) buildAllExcerpt() {
146 c.excerpts = make(map[string]BugExcerpt)
147
148 allBugs := bug.ReadAllLocalBugs(c.repo)
149
150 for b := range allBugs {
151 snap := b.Bug.Compile()
152 c.excerpts[b.Bug.Id()] = NewBugExcerpt(b.Bug, &snap)
153 }
154}
155
156func (c *RepoCache) allExcerpt() []BugExcerpt {
157 result := make([]BugExcerpt, len(c.excerpts))
158
159 i := 0
160 for _, val := range c.excerpts {
161 result[i] = val
162 i++
163 }
164
165 return result
166}
167
168func (c *RepoCache) ResolveBug(id string) (*BugCache, error) {
169 cached, ok := c.bugs[id]
170 if ok {
171 return cached, nil
172 }
173
174 b, err := bug.ReadLocalBug(c.repo, id)
175 if err != nil {
176 return nil, err
177 }
178
179 cached = NewBugCache(c, b)
180 c.bugs[id] = cached
181
182 return cached, nil
183}
184
185func (c *RepoCache) ResolveBugPrefix(prefix string) (*BugCache, error) {
186 // preallocate but empty
187 matching := make([]string, 0, 5)
188
189 for id := range c.bugs {
190 if strings.HasPrefix(id, prefix) {
191 matching = append(matching, id)
192 }
193 }
194
195 // TODO: should check matching bug in the repo as well
196
197 if len(matching) > 1 {
198 return nil, fmt.Errorf("Multiple matching bug found:\n%s", strings.Join(matching, "\n"))
199 }
200
201 if len(matching) == 1 {
202 b := c.bugs[matching[0]]
203 return b, nil
204 }
205
206 b, err := bug.FindLocalBug(c.repo, prefix)
207
208 if err != nil {
209 return nil, err
210 }
211
212 cached := NewBugCache(c, b)
213 c.bugs[b.Id()] = cached
214
215 return cached, nil
216}
217
218// ClearAllBugs clear all bugs kept in memory
219func (c *RepoCache) ClearAllBugs() {
220 c.bugs = make(map[string]*BugCache)
221}
222
223// NewBug create a new bug
224// The new bug is written in the repository (commit)
225func (c *RepoCache) NewBug(title string, message string) (*BugCache, error) {
226 return c.NewBugWithFiles(title, message, nil)
227}
228
229// NewBugWithFiles create a new bug with attached files for the message
230// The new bug is written in the repository (commit)
231func (c *RepoCache) NewBugWithFiles(title string, message string, files []util.Hash) (*BugCache, error) {
232 author, err := bug.GetUser(c.repo)
233 if err != nil {
234 return nil, err
235 }
236
237 b, err := operations.CreateWithFiles(author, title, message, files)
238 if err != nil {
239 return nil, err
240 }
241
242 err = b.Commit(c.repo)
243 if err != nil {
244 return nil, err
245 }
246
247 cached := NewBugCache(c, b)
248 c.bugs[b.Id()] = cached
249
250 err = c.bugUpdated(b.Id())
251 if err != nil {
252 return nil, err
253 }
254
255 return cached, nil
256}
257
258// Fetch retrieve update from a remote
259// This does not change the local bugs state
260func (c *RepoCache) Fetch(remote string) (string, error) {
261 return bug.Fetch(c.repo, remote)
262}
263
264// MergeAll will merge all the available remote bug
265func (c *RepoCache) MergeAll(remote string) <-chan bug.MergeResult {
266 out := make(chan bug.MergeResult)
267
268 // Intercept merge results to update the cache properly
269 go func() {
270 defer close(out)
271
272 results := bug.MergeAll(c.repo, remote)
273 for result := range results {
274 if result.Err != nil {
275 continue
276 }
277
278 id := result.Id
279
280 switch result.Status {
281 case bug.MsgMergeNew, bug.MsgMergeUpdated:
282 b := result.Bug
283 snap := b.Compile()
284 c.excerpts[id] = NewBugExcerpt(b, &snap)
285
286 default:
287 }
288
289 out <- result
290 }
291
292 err := c.writeExcerpts()
293
294 // No easy way out here ..
295 if err != nil {
296 panic(err)
297 }
298 }()
299
300 return out
301}
302
303// Push update a remote with the local changes
304func (c *RepoCache) Push(remote string) (string, error) {
305 return bug.Push(c.repo, remote)
306}
307
308func repoLockFilePath(repo repository.Repo) string {
309 return path.Join(repo.GetPath(), ".git", "git-bug", lockfile)
310}
311
312// repoIsAvailable check is the given repository is locked by a Cache.
313// Note: this is a smart function that will cleanup the lock file if the
314// corresponding process is not there anymore.
315// If no error is returned, the repo is free to edit.
316func repoIsAvailable(repo repository.Repo) error {
317 lockPath := repoLockFilePath(repo)
318
319 // Todo: this leave way for a racey access to the repo between the test
320 // if the file exist and the actual write. It's probably not a problem in
321 // practice because using a repository will be done from user interaction
322 // or in a context where a single instance of git-bug is already guaranteed
323 // (say, a server with the web UI running). But still, that might be nice to
324 // have a mutex or something to guard that.
325
326 // Todo: this will fail if somehow the filesystem is shared with another
327 // computer. Should add a configuration that prevent the cleaning of the
328 // lock file
329
330 f, err := os.Open(lockPath)
331
332 if err != nil && !os.IsNotExist(err) {
333 return err
334 }
335
336 if err == nil {
337 // lock file already exist
338 buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
339 if err != nil {
340 return err
341 }
342 if len(buf) == 10 {
343 return fmt.Errorf("The lock file should be < 10 bytes")
344 }
345
346 pid, err := strconv.Atoi(string(buf))
347 if err != nil {
348 return err
349 }
350
351 if util.ProcessIsRunning(pid) {
352 return fmt.Errorf("The repository you want to access is already locked by the process pid %d", pid)
353 }
354
355 // The lock file is just laying there after a crash, clean it
356
357 fmt.Println("A lock file is present but the corresponding process is not, removing it.")
358 err = f.Close()
359 if err != nil {
360 return err
361 }
362
363 os.Remove(lockPath)
364 if err != nil {
365 return err
366 }
367 }
368
369 return nil
370}