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