repo_cache.go

  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
264func (c *RepoCache) MergeAll(remote string) <-chan bug.MergeResult {
265	// Todo: update the cache properly
266	return bug.MergeAll(c.repo, remote)
267}
268
269// Push update a remote with the local changes
270func (c *RepoCache) Push(remote string) (string, error) {
271	return bug.Push(c.repo, remote)
272}
273
274func repoLockFilePath(repo repository.Repo) string {
275	return path.Join(repo.GetPath(), ".git", "git-bug", lockfile)
276}
277
278// repoIsAvailable check is the given repository is locked by a Cache.
279// Note: this is a smart function that will cleanup the lock file if the
280// corresponding process is not there anymore.
281// If no error is returned, the repo is free to edit.
282func repoIsAvailable(repo repository.Repo) error {
283	lockPath := repoLockFilePath(repo)
284
285	// Todo: this leave way for a racey access to the repo between the test
286	// if the file exist and the actual write. It's probably not a problem in
287	// practice because using a repository will be done from user interaction
288	// or in a context where a single instance of git-bug is already guaranteed
289	// (say, a server with the web UI running). But still, that might be nice to
290	// have a mutex or something to guard that.
291
292	// Todo: this will fail if somehow the filesystem is shared with another
293	// computer. Should add a configuration that prevent the cleaning of the
294	// lock file
295
296	f, err := os.Open(lockPath)
297
298	if err != nil && !os.IsNotExist(err) {
299		return err
300	}
301
302	if err == nil {
303		// lock file already exist
304		buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
305		if err != nil {
306			return err
307		}
308		if len(buf) == 10 {
309			return fmt.Errorf("The lock file should be < 10 bytes")
310		}
311
312		pid, err := strconv.Atoi(string(buf))
313		if err != nil {
314			return err
315		}
316
317		if util.ProcessIsRunning(pid) {
318			return fmt.Errorf("The repository you want to access is already locked by the process pid %d", pid)
319		}
320
321		// The lock file is just laying there after a crash, clean it
322
323		fmt.Println("A lock file is present but the corresponding process is not, removing it.")
324		err = f.Close()
325		if err != nil {
326			return err
327		}
328
329		os.Remove(lockPath)
330		if err != nil {
331			return err
332		}
333	}
334
335	return nil
336}