bug.go

  1// Package bug contains the bug data model and low-level related functions
  2package bug
  3
  4import (
  5	"encoding/json"
  6	"fmt"
  7	"strings"
  8
  9	"github.com/pkg/errors"
 10
 11	"github.com/MichaelMure/git-bug/entity"
 12	"github.com/MichaelMure/git-bug/identity"
 13	"github.com/MichaelMure/git-bug/repository"
 14	"github.com/MichaelMure/git-bug/util/lamport"
 15)
 16
 17const bugsRefPattern = "refs/bugs/"
 18const bugsRemoteRefPattern = "refs/remotes/%s/bugs/"
 19
 20const opsEntryName = "ops"
 21const rootEntryName = "root"
 22const mediaEntryName = "media"
 23
 24const createClockEntryPrefix = "create-clock-"
 25const createClockEntryPattern = "create-clock-%d"
 26const editClockEntryPrefix = "edit-clock-"
 27const editClockEntryPattern = "edit-clock-%d"
 28
 29const creationClockName = "bug-create"
 30const editClockName = "bug-edit"
 31
 32var ErrBugNotExist = errors.New("bug doesn't exist")
 33
 34func NewErrMultipleMatchBug(matching []entity.Id) *entity.ErrMultipleMatch {
 35	return entity.NewErrMultipleMatch("bug", matching)
 36}
 37
 38func NewErrMultipleMatchOp(matching []entity.Id) *entity.ErrMultipleMatch {
 39	return entity.NewErrMultipleMatch("operation", matching)
 40}
 41
 42var _ Interface = &Bug{}
 43var _ entity.Interface = &Bug{}
 44
 45// Bug hold the data of a bug thread, organized in a way close to
 46// how it will be persisted inside Git. This is the data structure
 47// used to merge two different version of the same Bug.
 48type Bug struct {
 49
 50	// A Lamport clock is a logical clock that allow to order event
 51	// inside a distributed system.
 52	// It must be the first field in this struct due to https://github.com/golang/go/issues/599
 53	createTime lamport.Time
 54	editTime   lamport.Time
 55
 56	// Id used as unique identifier
 57	id entity.Id
 58
 59	lastCommit repository.Hash
 60	rootPack   repository.Hash
 61
 62	// all the committed operations
 63	packs []OperationPack
 64
 65	// a temporary pack of operations used for convenience to pile up new operations
 66	// before a commit
 67	staging OperationPack
 68}
 69
 70// NewBug create a new Bug
 71func NewBug() *Bug {
 72	// No id yet
 73	// No logical clock yet
 74	return &Bug{}
 75}
 76
 77// FindLocalBug find an existing Bug matching a prefix
 78func FindLocalBug(repo repository.ClockedRepo, prefix string) (*Bug, error) {
 79	ids, err := ListLocalIds(repo)
 80
 81	if err != nil {
 82		return nil, err
 83	}
 84
 85	// preallocate but empty
 86	matching := make([]entity.Id, 0, 5)
 87
 88	for _, id := range ids {
 89		if id.HasPrefix(prefix) {
 90			matching = append(matching, id)
 91		}
 92	}
 93
 94	if len(matching) == 0 {
 95		return nil, errors.New("no matching bug found.")
 96	}
 97
 98	if len(matching) > 1 {
 99		return nil, NewErrMultipleMatchBug(matching)
100	}
101
102	return ReadLocalBug(repo, matching[0])
103}
104
105// ReadLocalBug will read a local bug from its hash
106func ReadLocalBug(repo repository.ClockedRepo, id entity.Id) (*Bug, error) {
107	ref := bugsRefPattern + id.String()
108	return readBug(repo, ref)
109}
110
111// ReadRemoteBug will read a remote bug from its hash
112func ReadRemoteBug(repo repository.ClockedRepo, remote string, id string) (*Bug, error) {
113	ref := fmt.Sprintf(bugsRemoteRefPattern, remote) + id
114	return readBug(repo, ref)
115}
116
117// readBug will read and parse a Bug from git
118func readBug(repo repository.ClockedRepo, ref string) (*Bug, error) {
119	refSplit := strings.Split(ref, "/")
120	id := entity.Id(refSplit[len(refSplit)-1])
121
122	if err := id.Validate(); err != nil {
123		return nil, errors.Wrap(err, "invalid ref ")
124	}
125
126	hashes, err := repo.ListCommits(ref)
127
128	// TODO: this is not perfect, it might be a command invoke error
129	if err != nil {
130		return nil, ErrBugNotExist
131	}
132
133	bug := Bug{
134		id:       id,
135		editTime: 0,
136	}
137
138	// Load each OperationPack
139	for _, hash := range hashes {
140		entries, err := repo.ReadTree(hash)
141		if err != nil {
142			return nil, errors.Wrap(err, "can't list git tree entries")
143		}
144
145		bug.lastCommit = hash
146
147		var opsEntry repository.TreeEntry
148		opsFound := false
149		var rootEntry repository.TreeEntry
150		rootFound := false
151		var createTime uint64
152		var editTime uint64
153
154		for _, entry := range entries {
155			if entry.Name == opsEntryName {
156				opsEntry = entry
157				opsFound = true
158				continue
159			}
160			if entry.Name == rootEntryName {
161				rootEntry = entry
162				rootFound = true
163			}
164			if strings.HasPrefix(entry.Name, createClockEntryPrefix) {
165				n, err := fmt.Sscanf(entry.Name, createClockEntryPattern, &createTime)
166				if err != nil {
167					return nil, errors.Wrap(err, "can't read create lamport time")
168				}
169				if n != 1 {
170					return nil, fmt.Errorf("could not parse create time lamport value")
171				}
172			}
173			if strings.HasPrefix(entry.Name, editClockEntryPrefix) {
174				n, err := fmt.Sscanf(entry.Name, editClockEntryPattern, &editTime)
175				if err != nil {
176					return nil, errors.Wrap(err, "can't read edit lamport time")
177				}
178				if n != 1 {
179					return nil, fmt.Errorf("could not parse edit time lamport value")
180				}
181			}
182		}
183
184		if !opsFound {
185			return nil, errors.New("invalid tree, missing the ops entry")
186		}
187		if !rootFound {
188			return nil, errors.New("invalid tree, missing the root entry")
189		}
190
191		if bug.rootPack == "" {
192			bug.rootPack = rootEntry.Hash
193			bug.createTime = lamport.Time(createTime)
194		}
195
196		// Due to rebase, edit Lamport time are not necessarily ordered
197		if editTime > uint64(bug.editTime) {
198			bug.editTime = lamport.Time(editTime)
199		}
200
201		// Update the clocks
202		createClock, err := repo.GetOrCreateClock(creationClockName)
203		if err != nil {
204			return nil, err
205		}
206		if err := createClock.Witness(bug.createTime); err != nil {
207			return nil, errors.Wrap(err, "failed to update create lamport clock")
208		}
209		editClock, err := repo.GetOrCreateClock(editClockName)
210		if err != nil {
211			return nil, err
212		}
213		if err := editClock.Witness(bug.editTime); err != nil {
214			return nil, errors.Wrap(err, "failed to update edit lamport clock")
215		}
216
217		data, err := repo.ReadData(opsEntry.Hash)
218		if err != nil {
219			return nil, errors.Wrap(err, "failed to read git blob data")
220		}
221
222		opp := &OperationPack{}
223		err = json.Unmarshal(data, &opp)
224
225		if err != nil {
226			return nil, errors.Wrap(err, "failed to decode OperationPack json")
227		}
228
229		// tag the pack with the commit hash
230		opp.commitHash = hash
231
232		bug.packs = append(bug.packs, *opp)
233	}
234
235	// Make sure that the identities are properly loaded
236	resolver := identity.NewSimpleResolver(repo)
237	err = bug.EnsureIdentities(resolver)
238	if err != nil {
239		return nil, err
240	}
241
242	return &bug, nil
243}
244
245func RemoveLocalBug(repo repository.ClockedRepo, id entity.Id) error {
246	ref := bugsRefPattern + id.String()
247	return repo.RemoveRef(ref)
248}
249
250type StreamedBug struct {
251	Bug *Bug
252	Err error
253}
254
255// ReadAllLocalBugs read and parse all local bugs
256func ReadAllLocalBugs(repo repository.ClockedRepo) <-chan StreamedBug {
257	return readAllBugs(repo, bugsRefPattern)
258}
259
260// ReadAllRemoteBugs read and parse all remote bugs for a given remote
261func ReadAllRemoteBugs(repo repository.ClockedRepo, remote string) <-chan StreamedBug {
262	refPrefix := fmt.Sprintf(bugsRemoteRefPattern, remote)
263	return readAllBugs(repo, refPrefix)
264}
265
266// Read and parse all available bug with a given ref prefix
267func readAllBugs(repo repository.ClockedRepo, refPrefix string) <-chan StreamedBug {
268	out := make(chan StreamedBug)
269
270	go func() {
271		defer close(out)
272
273		refs, err := repo.ListRefs(refPrefix)
274		if err != nil {
275			out <- StreamedBug{Err: err}
276			return
277		}
278
279		for _, ref := range refs {
280			b, err := readBug(repo, ref)
281
282			if err != nil {
283				out <- StreamedBug{Err: err}
284				return
285			}
286
287			out <- StreamedBug{Bug: b}
288		}
289	}()
290
291	return out
292}
293
294// ListLocalIds list all the available local bug ids
295func ListLocalIds(repo repository.Repo) ([]entity.Id, error) {
296	refs, err := repo.ListRefs(bugsRefPattern)
297	if err != nil {
298		return nil, err
299	}
300
301	return refsToIds(refs), nil
302}
303
304func refsToIds(refs []string) []entity.Id {
305	ids := make([]entity.Id, len(refs))
306
307	for i, ref := range refs {
308		split := strings.Split(ref, "/")
309		ids[i] = entity.Id(split[len(split)-1])
310	}
311
312	return ids
313}
314
315// Validate check if the Bug data is valid
316func (bug *Bug) Validate() error {
317	// non-empty
318	if len(bug.packs) == 0 && bug.staging.IsEmpty() {
319		return fmt.Errorf("bug has no operations")
320	}
321
322	// check if each pack and operations are valid
323	for _, pack := range bug.packs {
324		if err := pack.Validate(); err != nil {
325			return err
326		}
327	}
328
329	// check if staging is valid if needed
330	if !bug.staging.IsEmpty() {
331		if err := bug.staging.Validate(); err != nil {
332			return errors.Wrap(err, "staging")
333		}
334	}
335
336	// The very first Op should be a CreateOp
337	firstOp := bug.FirstOp()
338	if firstOp == nil || firstOp.base().OperationType != CreateOp {
339		return fmt.Errorf("first operation should be a Create op")
340	}
341
342	// The bug Id should be the hash of the first commit
343	if len(bug.packs) > 0 && string(bug.packs[0].commitHash) != bug.id.String() {
344		return fmt.Errorf("bug id should be the first commit hash")
345	}
346
347	// Check that there is no more CreateOp op
348	// Check that there is no colliding operation's ID
349	it := NewOperationIterator(bug)
350	createCount := 0
351	ids := make(map[entity.Id]struct{})
352	for it.Next() {
353		if it.Value().base().OperationType == CreateOp {
354			createCount++
355		}
356		if _, ok := ids[it.Value().Id()]; ok {
357			return fmt.Errorf("id collision: %s", it.Value().Id())
358		}
359		ids[it.Value().Id()] = struct{}{}
360	}
361
362	if createCount != 1 {
363		return fmt.Errorf("only one Create op allowed")
364	}
365
366	return nil
367}
368
369// Append an operation into the staging area, to be committed later
370func (bug *Bug) Append(op Operation) {
371	bug.staging.Append(op)
372}
373
374// Commit write the staging area in Git and move the operations to the packs
375func (bug *Bug) Commit(repo repository.ClockedRepo) error {
376
377	if !bug.NeedCommit() {
378		return fmt.Errorf("can't commit a bug with no pending operation")
379	}
380
381	if err := bug.Validate(); err != nil {
382		return errors.Wrap(err, "can't commit a bug with invalid data")
383	}
384
385	// Write the Ops as a Git blob containing the serialized array
386	hash, err := bug.staging.Write(repo)
387	if err != nil {
388		return err
389	}
390
391	if bug.rootPack == "" {
392		bug.rootPack = hash
393	}
394
395	// Make a Git tree referencing this blob
396	tree := []repository.TreeEntry{
397		// the last pack of ops
398		{ObjectType: repository.Blob, Hash: hash, Name: opsEntryName},
399		// always the first pack of ops (might be the same)
400		{ObjectType: repository.Blob, Hash: bug.rootPack, Name: rootEntryName},
401	}
402
403	// Reference, if any, all the files required by the ops
404	// Git will check that they actually exist in the storage and will make sure
405	// to push/pull them as needed.
406	mediaTree := makeMediaTree(bug.staging)
407	if len(mediaTree) > 0 {
408		mediaTreeHash, err := repo.StoreTree(mediaTree)
409		if err != nil {
410			return err
411		}
412		tree = append(tree, repository.TreeEntry{
413			ObjectType: repository.Tree,
414			Hash:       mediaTreeHash,
415			Name:       mediaEntryName,
416		})
417	}
418
419	// Store the logical clocks as well
420	// --> edit clock for each OperationPack/commits
421	// --> create clock only for the first OperationPack/commits
422	//
423	// To avoid having one blob for each clock value, clocks are serialized
424	// directly into the entry name
425	emptyBlobHash, err := repo.StoreData([]byte{})
426	if err != nil {
427		return err
428	}
429
430	editClock, err := repo.GetOrCreateClock(editClockName)
431	if err != nil {
432		return err
433	}
434	bug.editTime, err = editClock.Increment()
435	if err != nil {
436		return err
437	}
438
439	tree = append(tree, repository.TreeEntry{
440		ObjectType: repository.Blob,
441		Hash:       emptyBlobHash,
442		Name:       fmt.Sprintf(editClockEntryPattern, bug.editTime),
443	})
444	if bug.lastCommit == "" {
445		createClock, err := repo.GetOrCreateClock(creationClockName)
446		if err != nil {
447			return err
448		}
449		bug.createTime, err = createClock.Increment()
450		if err != nil {
451			return err
452		}
453
454		tree = append(tree, repository.TreeEntry{
455			ObjectType: repository.Blob,
456			Hash:       emptyBlobHash,
457			Name:       fmt.Sprintf(createClockEntryPattern, bug.createTime),
458		})
459	}
460
461	// Store the tree
462	hash, err = repo.StoreTree(tree)
463	if err != nil {
464		return err
465	}
466
467	// Write a Git commit referencing the tree, with the previous commit as parent
468	if bug.lastCommit != "" {
469		hash, err = repo.StoreCommitWithParent(hash, bug.lastCommit)
470	} else {
471		hash, err = repo.StoreCommit(hash)
472	}
473
474	if err != nil {
475		return err
476	}
477
478	bug.lastCommit = hash
479
480	// if it was the first commit, use the commit hash as bug id
481	if bug.id == "" {
482		bug.id = entity.Id(hash)
483	}
484
485	// Create or update the Git reference for this bug
486	// When pushing later, the remote will ensure that this ref update
487	// is fast-forward, that is no data has been overwritten
488	ref := fmt.Sprintf("%s%s", bugsRefPattern, bug.id)
489	err = repo.UpdateRef(ref, hash)
490
491	if err != nil {
492		return err
493	}
494
495	bug.staging.commitHash = hash
496	bug.packs = append(bug.packs, bug.staging)
497	bug.staging = OperationPack{}
498
499	return nil
500}
501
502func (bug *Bug) CommitAsNeeded(repo repository.ClockedRepo) error {
503	if !bug.NeedCommit() {
504		return nil
505	}
506	return bug.Commit(repo)
507}
508
509func (bug *Bug) NeedCommit() bool {
510	return !bug.staging.IsEmpty()
511}
512
513func makeMediaTree(pack OperationPack) []repository.TreeEntry {
514	var tree []repository.TreeEntry
515	counter := 0
516	added := make(map[repository.Hash]interface{})
517
518	for _, ops := range pack.Operations {
519		for _, file := range ops.GetFiles() {
520			if _, has := added[file]; !has {
521				tree = append(tree, repository.TreeEntry{
522					ObjectType: repository.Blob,
523					Hash:       file,
524					// The name is not important here, we only need to
525					// reference the blob.
526					Name: fmt.Sprintf("file%d", counter),
527				})
528				counter++
529				added[file] = struct{}{}
530			}
531		}
532	}
533
534	return tree
535}
536
537// Merge a different version of the same bug by rebasing operations of this bug
538// that are not present in the other on top of the chain of operations of the
539// other version.
540func (bug *Bug) Merge(repo repository.Repo, other Interface) (bool, error) {
541	var otherBug = bugFromInterface(other)
542
543	// Note: a faster merge should be possible without actually reading and parsing
544	// all operations pack of our side.
545	// Reading the other side is still necessary to validate remote data, at least
546	// for new operations
547
548	if bug.id != otherBug.id {
549		return false, errors.New("merging unrelated bugs is not supported")
550	}
551
552	if len(otherBug.staging.Operations) > 0 {
553		return false, errors.New("merging a bug with a non-empty staging is not supported")
554	}
555
556	if bug.lastCommit == "" || otherBug.lastCommit == "" {
557		return false, errors.New("can't merge a bug that has never been stored")
558	}
559
560	ancestor, err := repo.FindCommonAncestor(bug.lastCommit, otherBug.lastCommit)
561	if err != nil {
562		return false, errors.Wrap(err, "can't find common ancestor")
563	}
564
565	ancestorIndex := 0
566	newPacks := make([]OperationPack, 0, len(bug.packs))
567
568	// Find the root of the rebase
569	for i, pack := range bug.packs {
570		newPacks = append(newPacks, pack)
571
572		if pack.commitHash == ancestor {
573			ancestorIndex = i
574			break
575		}
576	}
577
578	if len(otherBug.packs) == ancestorIndex+1 {
579		// Nothing to rebase, return early
580		return false, nil
581	}
582
583	// get other bug's extra packs
584	for i := ancestorIndex + 1; i < len(otherBug.packs); i++ {
585		// clone is probably not necessary
586		newPack := otherBug.packs[i].Clone()
587
588		newPacks = append(newPacks, newPack)
589		bug.lastCommit = newPack.commitHash
590	}
591
592	// rebase our extra packs
593	for i := ancestorIndex + 1; i < len(bug.packs); i++ {
594		pack := bug.packs[i]
595
596		// get the referenced git tree
597		treeHash, err := repo.GetTreeHash(pack.commitHash)
598
599		if err != nil {
600			return false, err
601		}
602
603		// create a new commit with the correct ancestor
604		hash, err := repo.StoreCommitWithParent(treeHash, bug.lastCommit)
605
606		if err != nil {
607			return false, err
608		}
609
610		// replace the pack
611		newPack := pack.Clone()
612		newPack.commitHash = hash
613		newPacks = append(newPacks, newPack)
614
615		// update the bug
616		bug.lastCommit = hash
617	}
618
619	bug.packs = newPacks
620
621	// Update the git ref
622	err = repo.UpdateRef(bugsRefPattern+bug.id.String(), bug.lastCommit)
623	if err != nil {
624		return false, err
625	}
626
627	return true, nil
628}
629
630// Id return the Bug identifier
631func (bug *Bug) Id() entity.Id {
632	if bug.id == "" {
633		// simply panic as it would be a coding error
634		// (using an id of a bug not stored yet)
635		panic("no id yet")
636	}
637	return bug.id
638}
639
640// CreateLamportTime return the Lamport time of creation
641func (bug *Bug) CreateLamportTime() lamport.Time {
642	return bug.createTime
643}
644
645// EditLamportTime return the Lamport time of the last edit
646func (bug *Bug) EditLamportTime() lamport.Time {
647	return bug.editTime
648}
649
650// Lookup for the very first operation of the bug.
651// For a valid Bug, this operation should be a CreateOp
652func (bug *Bug) FirstOp() Operation {
653	for _, pack := range bug.packs {
654		for _, op := range pack.Operations {
655			return op
656		}
657	}
658
659	if !bug.staging.IsEmpty() {
660		return bug.staging.Operations[0]
661	}
662
663	return nil
664}
665
666// Lookup for the very last operation of the bug.
667// For a valid Bug, should never be nil
668func (bug *Bug) LastOp() Operation {
669	if !bug.staging.IsEmpty() {
670		return bug.staging.Operations[len(bug.staging.Operations)-1]
671	}
672
673	if len(bug.packs) == 0 {
674		return nil
675	}
676
677	lastPack := bug.packs[len(bug.packs)-1]
678
679	if len(lastPack.Operations) == 0 {
680		return nil
681	}
682
683	return lastPack.Operations[len(lastPack.Operations)-1]
684}
685
686// Compile a bug in a easily usable snapshot
687func (bug *Bug) Compile() Snapshot {
688	snap := Snapshot{
689		id:     bug.id,
690		Status: OpenStatus,
691	}
692
693	it := NewOperationIterator(bug)
694
695	for it.Next() {
696		op := it.Value()
697		op.Apply(&snap)
698		snap.Operations = append(snap.Operations, op)
699	}
700
701	return snap
702}