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) ResolveBug(id string) (*BugCache, error) {
157	cached, ok := c.bugs[id]
158	if ok {
159		return cached, nil
160	}
161
162	b, err := bug.ReadLocalBug(c.repo, id)
163	if err != nil {
164		return nil, err
165	}
166
167	cached = NewBugCache(c, b)
168	c.bugs[id] = cached
169
170	return cached, nil
171}
172
173func (c *RepoCache) ResolveBugPrefix(prefix string) (*BugCache, error) {
174	// preallocate but empty
175	matching := make([]string, 0, 5)
176
177	for id := range c.bugs {
178		if strings.HasPrefix(id, prefix) {
179			matching = append(matching, id)
180		}
181	}
182
183	// TODO: should check matching bug in the repo as well
184
185	if len(matching) > 1 {
186		return nil, fmt.Errorf("Multiple matching bug found:\n%s", strings.Join(matching, "\n"))
187	}
188
189	if len(matching) == 1 {
190		b := c.bugs[matching[0]]
191		return b, nil
192	}
193
194	b, err := bug.FindLocalBug(c.repo, prefix)
195
196	if err != nil {
197		return nil, err
198	}
199
200	cached := NewBugCache(c, b)
201	c.bugs[b.Id()] = cached
202
203	return cached, nil
204}
205
206func (c *RepoCache) AllBugIds() ([]string, error) {
207	return bug.ListLocalIds(c.repo)
208}
209
210// ClearAllBugs clear all bugs kept in memory
211func (c *RepoCache) ClearAllBugs() {
212	c.bugs = make(map[string]*BugCache)
213}
214
215// NewBug create a new bug
216// The new bug is written in the repository (commit)
217func (c *RepoCache) NewBug(title string, message string) (*BugCache, error) {
218	return c.NewBugWithFiles(title, message, nil)
219}
220
221// NewBugWithFiles create a new bug with attached files for the message
222// The new bug is written in the repository (commit)
223func (c *RepoCache) NewBugWithFiles(title string, message string, files []util.Hash) (*BugCache, error) {
224	author, err := bug.GetUser(c.repo)
225	if err != nil {
226		return nil, err
227	}
228
229	b, err := operations.CreateWithFiles(author, title, message, files)
230	if err != nil {
231		return nil, err
232	}
233
234	err = b.Commit(c.repo)
235	if err != nil {
236		return nil, err
237	}
238
239	cached := NewBugCache(c, b)
240	c.bugs[b.Id()] = cached
241
242	return cached, nil
243}
244
245// Fetch retrieve update from a remote
246// This does not change the local bugs state
247func (c *RepoCache) Fetch(remote string) (string, error) {
248	return bug.Fetch(c.repo, remote)
249}
250
251func (c *RepoCache) MergeAll(remote string) <-chan bug.MergeResult {
252	return bug.MergeAll(c.repo, remote)
253}
254
255// Pull does a Fetch and merge the updates into the local bug states
256func (c *RepoCache) Pull(remote string, out io.Writer) error {
257	return bug.Pull(c.repo, out, remote)
258}
259
260// Push update a remote with the local changes
261func (c *RepoCache) Push(remote string) (string, error) {
262	return bug.Push(c.repo, remote)
263}
264
265func repoLockFilePath(repo repository.Repo) string {
266	return path.Join(repo.GetPath(), ".git", "git-bug", lockfile)
267}
268
269// repoIsAvailable check is the given repository is locked by a Cache.
270// Note: this is a smart function that will cleanup the lock file if the
271// corresponding process is not there anymore.
272// If no error is returned, the repo is free to edit.
273func repoIsAvailable(repo repository.Repo) error {
274	lockPath := repoLockFilePath(repo)
275
276	// Todo: this leave way for a racey access to the repo between the test
277	// if the file exist and the actual write. It's probably not a problem in
278	// practice because using a repository will be done from user interaction
279	// or in a context where a single instance of git-bug is already guaranteed
280	// (say, a server with the web UI running). But still, that might be nice to
281	// have a mutex or something to guard that.
282
283	// Todo: this will fail if somehow the filesystem is shared with another
284	// computer. Should add a configuration that prevent the cleaning of the
285	// lock file
286
287	f, err := os.Open(lockPath)
288
289	if err != nil && !os.IsNotExist(err) {
290		return err
291	}
292
293	if err == nil {
294		// lock file already exist
295		buf, err := ioutil.ReadAll(io.LimitReader(f, 10))
296		if err != nil {
297			return err
298		}
299		if len(buf) == 10 {
300			return fmt.Errorf("The lock file should be < 10 bytes")
301		}
302
303		pid, err := strconv.Atoi(string(buf))
304		if err != nil {
305			return err
306		}
307
308		if util.ProcessIsRunning(pid) {
309			return fmt.Errorf("The repository you want to access is already locked by the process pid %d", pid)
310		}
311
312		// The lock file is just laying there after a crash, clean it
313
314		fmt.Println("A lock file is present but the corresponding process is not, removing it.")
315		err = f.Close()
316		if err != nil {
317			return err
318		}
319
320		os.Remove(lockPath)
321		if err != nil {
322			return err
323		}
324	}
325
326	return nil
327}