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
245// RemoveLocalBug will remove a local bug from its hash
246func RemoveBug(repo repository.ClockedRepo, id entity.Id) error {
247 refs, err := repo.ListRefs(id.String())
248 if err != nil {
249 return err
250 }
251 for _, ref := range refs {
252 err = repo.RemoveRef(ref)
253 if err != nil {
254 return err
255 }
256 }
257 return nil
258}
259
260type StreamedBug struct {
261 Bug *Bug
262 Err error
263}
264
265// ReadAllLocalBugs read and parse all local bugs
266func ReadAllLocalBugs(repo repository.ClockedRepo) <-chan StreamedBug {
267 return readAllBugs(repo, bugsRefPattern)
268}
269
270// ReadAllRemoteBugs read and parse all remote bugs for a given remote
271func ReadAllRemoteBugs(repo repository.ClockedRepo, remote string) <-chan StreamedBug {
272 refPrefix := fmt.Sprintf(bugsRemoteRefPattern, remote)
273 return readAllBugs(repo, refPrefix)
274}
275
276// Read and parse all available bug with a given ref prefix
277func readAllBugs(repo repository.ClockedRepo, refPrefix string) <-chan StreamedBug {
278 out := make(chan StreamedBug)
279
280 go func() {
281 defer close(out)
282
283 refs, err := repo.ListRefs(refPrefix)
284 if err != nil {
285 out <- StreamedBug{Err: err}
286 return
287 }
288
289 for _, ref := range refs {
290 b, err := readBug(repo, ref)
291
292 if err != nil {
293 out <- StreamedBug{Err: err}
294 return
295 }
296
297 out <- StreamedBug{Bug: b}
298 }
299 }()
300
301 return out
302}
303
304// ListLocalIds list all the available local bug ids
305func ListLocalIds(repo repository.Repo) ([]entity.Id, error) {
306 refs, err := repo.ListRefs(bugsRefPattern)
307 if err != nil {
308 return nil, err
309 }
310
311 return refsToIds(refs), nil
312}
313
314func refsToIds(refs []string) []entity.Id {
315 ids := make([]entity.Id, len(refs))
316
317 for i, ref := range refs {
318 split := strings.Split(ref, "/")
319 ids[i] = entity.Id(split[len(split)-1])
320 }
321
322 return ids
323}
324
325// Validate check if the Bug data is valid
326func (bug *Bug) Validate() error {
327 // non-empty
328 if len(bug.packs) == 0 && bug.staging.IsEmpty() {
329 return fmt.Errorf("bug has no operations")
330 }
331
332 // check if each pack and operations are valid
333 for _, pack := range bug.packs {
334 if err := pack.Validate(); err != nil {
335 return err
336 }
337 }
338
339 // check if staging is valid if needed
340 if !bug.staging.IsEmpty() {
341 if err := bug.staging.Validate(); err != nil {
342 return errors.Wrap(err, "staging")
343 }
344 }
345
346 // The very first Op should be a CreateOp
347 firstOp := bug.FirstOp()
348 if firstOp == nil || firstOp.base().OperationType != CreateOp {
349 return fmt.Errorf("first operation should be a Create op")
350 }
351
352 // The bug Id should be the hash of the first commit
353 if len(bug.packs) > 0 && string(bug.packs[0].commitHash) != bug.id.String() {
354 return fmt.Errorf("bug id should be the first commit hash")
355 }
356
357 // Check that there is no more CreateOp op
358 // Check that there is no colliding operation's ID
359 it := NewOperationIterator(bug)
360 createCount := 0
361 ids := make(map[entity.Id]struct{})
362 for it.Next() {
363 if it.Value().base().OperationType == CreateOp {
364 createCount++
365 }
366 if _, ok := ids[it.Value().Id()]; ok {
367 return fmt.Errorf("id collision: %s", it.Value().Id())
368 }
369 ids[it.Value().Id()] = struct{}{}
370 }
371
372 if createCount != 1 {
373 return fmt.Errorf("only one Create op allowed")
374 }
375
376 return nil
377}
378
379// Append an operation into the staging area, to be committed later
380func (bug *Bug) Append(op Operation) {
381 bug.staging.Append(op)
382}
383
384// Commit write the staging area in Git and move the operations to the packs
385func (bug *Bug) Commit(repo repository.ClockedRepo) error {
386
387 if !bug.NeedCommit() {
388 return fmt.Errorf("can't commit a bug with no pending operation")
389 }
390
391 if err := bug.Validate(); err != nil {
392 return errors.Wrap(err, "can't commit a bug with invalid data")
393 }
394
395 // Write the Ops as a Git blob containing the serialized array
396 hash, err := bug.staging.Write(repo)
397 if err != nil {
398 return err
399 }
400
401 if bug.rootPack == "" {
402 bug.rootPack = hash
403 }
404
405 // Make a Git tree referencing this blob
406 tree := []repository.TreeEntry{
407 // the last pack of ops
408 {ObjectType: repository.Blob, Hash: hash, Name: opsEntryName},
409 // always the first pack of ops (might be the same)
410 {ObjectType: repository.Blob, Hash: bug.rootPack, Name: rootEntryName},
411 }
412
413 // Reference, if any, all the files required by the ops
414 // Git will check that they actually exist in the storage and will make sure
415 // to push/pull them as needed.
416 mediaTree := makeMediaTree(bug.staging)
417 if len(mediaTree) > 0 {
418 mediaTreeHash, err := repo.StoreTree(mediaTree)
419 if err != nil {
420 return err
421 }
422 tree = append(tree, repository.TreeEntry{
423 ObjectType: repository.Tree,
424 Hash: mediaTreeHash,
425 Name: mediaEntryName,
426 })
427 }
428
429 // Store the logical clocks as well
430 // --> edit clock for each OperationPack/commits
431 // --> create clock only for the first OperationPack/commits
432 //
433 // To avoid having one blob for each clock value, clocks are serialized
434 // directly into the entry name
435 emptyBlobHash, err := repo.StoreData([]byte{})
436 if err != nil {
437 return err
438 }
439
440 editClock, err := repo.GetOrCreateClock(editClockName)
441 if err != nil {
442 return err
443 }
444 bug.editTime, err = editClock.Increment()
445 if err != nil {
446 return err
447 }
448
449 tree = append(tree, repository.TreeEntry{
450 ObjectType: repository.Blob,
451 Hash: emptyBlobHash,
452 Name: fmt.Sprintf(editClockEntryPattern, bug.editTime),
453 })
454 if bug.lastCommit == "" {
455 createClock, err := repo.GetOrCreateClock(creationClockName)
456 if err != nil {
457 return err
458 }
459 bug.createTime, err = createClock.Increment()
460 if err != nil {
461 return err
462 }
463
464 tree = append(tree, repository.TreeEntry{
465 ObjectType: repository.Blob,
466 Hash: emptyBlobHash,
467 Name: fmt.Sprintf(createClockEntryPattern, bug.createTime),
468 })
469 }
470
471 // Store the tree
472 hash, err = repo.StoreTree(tree)
473 if err != nil {
474 return err
475 }
476
477 // Write a Git commit referencing the tree, with the previous commit as parent
478 if bug.lastCommit != "" {
479 hash, err = repo.StoreCommitWithParent(hash, bug.lastCommit)
480 } else {
481 hash, err = repo.StoreCommit(hash)
482 }
483
484 if err != nil {
485 return err
486 }
487
488 bug.lastCommit = hash
489
490 // if it was the first commit, use the commit hash as bug id
491 if bug.id == "" {
492 bug.id = entity.Id(hash)
493 }
494
495 // Create or update the Git reference for this bug
496 // When pushing later, the remote will ensure that this ref update
497 // is fast-forward, that is no data has been overwritten
498 ref := fmt.Sprintf("%s%s", bugsRefPattern, bug.id)
499 err = repo.UpdateRef(ref, hash)
500
501 if err != nil {
502 return err
503 }
504
505 bug.staging.commitHash = hash
506 bug.packs = append(bug.packs, bug.staging)
507 bug.staging = OperationPack{}
508
509 return nil
510}
511
512func (bug *Bug) CommitAsNeeded(repo repository.ClockedRepo) error {
513 if !bug.NeedCommit() {
514 return nil
515 }
516 return bug.Commit(repo)
517}
518
519func (bug *Bug) NeedCommit() bool {
520 return !bug.staging.IsEmpty()
521}
522
523func makeMediaTree(pack OperationPack) []repository.TreeEntry {
524 var tree []repository.TreeEntry
525 counter := 0
526 added := make(map[repository.Hash]interface{})
527
528 for _, ops := range pack.Operations {
529 for _, file := range ops.GetFiles() {
530 if _, has := added[file]; !has {
531 tree = append(tree, repository.TreeEntry{
532 ObjectType: repository.Blob,
533 Hash: file,
534 // The name is not important here, we only need to
535 // reference the blob.
536 Name: fmt.Sprintf("file%d", counter),
537 })
538 counter++
539 added[file] = struct{}{}
540 }
541 }
542 }
543
544 return tree
545}
546
547// Merge a different version of the same bug by rebasing operations of this bug
548// that are not present in the other on top of the chain of operations of the
549// other version.
550func (bug *Bug) Merge(repo repository.Repo, other Interface) (bool, error) {
551 var otherBug = bugFromInterface(other)
552
553 // Note: a faster merge should be possible without actually reading and parsing
554 // all operations pack of our side.
555 // Reading the other side is still necessary to validate remote data, at least
556 // for new operations
557
558 if bug.id != otherBug.id {
559 return false, errors.New("merging unrelated bugs is not supported")
560 }
561
562 if len(otherBug.staging.Operations) > 0 {
563 return false, errors.New("merging a bug with a non-empty staging is not supported")
564 }
565
566 if bug.lastCommit == "" || otherBug.lastCommit == "" {
567 return false, errors.New("can't merge a bug that has never been stored")
568 }
569
570 ancestor, err := repo.FindCommonAncestor(bug.lastCommit, otherBug.lastCommit)
571 if err != nil {
572 return false, errors.Wrap(err, "can't find common ancestor")
573 }
574
575 ancestorIndex := 0
576 newPacks := make([]OperationPack, 0, len(bug.packs))
577
578 // Find the root of the rebase
579 for i, pack := range bug.packs {
580 newPacks = append(newPacks, pack)
581
582 if pack.commitHash == ancestor {
583 ancestorIndex = i
584 break
585 }
586 }
587
588 if len(otherBug.packs) == ancestorIndex+1 {
589 // Nothing to rebase, return early
590 return false, nil
591 }
592
593 // get other bug's extra packs
594 for i := ancestorIndex + 1; i < len(otherBug.packs); i++ {
595 // clone is probably not necessary
596 newPack := otherBug.packs[i].Clone()
597
598 newPacks = append(newPacks, newPack)
599 bug.lastCommit = newPack.commitHash
600 }
601
602 // rebase our extra packs
603 for i := ancestorIndex + 1; i < len(bug.packs); i++ {
604 pack := bug.packs[i]
605
606 // get the referenced git tree
607 treeHash, err := repo.GetTreeHash(pack.commitHash)
608
609 if err != nil {
610 return false, err
611 }
612
613 // create a new commit with the correct ancestor
614 hash, err := repo.StoreCommitWithParent(treeHash, bug.lastCommit)
615
616 if err != nil {
617 return false, err
618 }
619
620 // replace the pack
621 newPack := pack.Clone()
622 newPack.commitHash = hash
623 newPacks = append(newPacks, newPack)
624
625 // update the bug
626 bug.lastCommit = hash
627 }
628
629 bug.packs = newPacks
630
631 // Update the git ref
632 err = repo.UpdateRef(bugsRefPattern+bug.id.String(), bug.lastCommit)
633 if err != nil {
634 return false, err
635 }
636
637 return true, nil
638}
639
640// Id return the Bug identifier
641func (bug *Bug) Id() entity.Id {
642 if bug.id == "" {
643 // simply panic as it would be a coding error
644 // (using an id of a bug not stored yet)
645 panic("no id yet")
646 }
647 return bug.id
648}
649
650// CreateLamportTime return the Lamport time of creation
651func (bug *Bug) CreateLamportTime() lamport.Time {
652 return bug.createTime
653}
654
655// EditLamportTime return the Lamport time of the last edit
656func (bug *Bug) EditLamportTime() lamport.Time {
657 return bug.editTime
658}
659
660// Lookup for the very first operation of the bug.
661// For a valid Bug, this operation should be a CreateOp
662func (bug *Bug) FirstOp() Operation {
663 for _, pack := range bug.packs {
664 for _, op := range pack.Operations {
665 return op
666 }
667 }
668
669 if !bug.staging.IsEmpty() {
670 return bug.staging.Operations[0]
671 }
672
673 return nil
674}
675
676// Lookup for the very last operation of the bug.
677// For a valid Bug, should never be nil
678func (bug *Bug) LastOp() Operation {
679 if !bug.staging.IsEmpty() {
680 return bug.staging.Operations[len(bug.staging.Operations)-1]
681 }
682
683 if len(bug.packs) == 0 {
684 return nil
685 }
686
687 lastPack := bug.packs[len(bug.packs)-1]
688
689 if len(lastPack.Operations) == 0 {
690 return nil
691 }
692
693 return lastPack.Operations[len(lastPack.Operations)-1]
694}
695
696// Compile a bug in a easily usable snapshot
697func (bug *Bug) Compile() Snapshot {
698 snap := Snapshot{
699 id: bug.id,
700 Status: OpenStatus,
701 }
702
703 it := NewOperationIterator(bug)
704
705 for it.Next() {
706 op := it.Value()
707 op.Apply(&snap)
708 snap.Operations = append(snap.Operations, op)
709 }
710
711 return snap
712}