| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | |
| 7 | "gorm.io/gorm" |
| 8 | |
| 9 | "amadan.net/oficina/mapa/internal/mapa/markup" |
| 10 | "amadan.net/oficina/mapa/internal/mapa/seal" |
| 11 | ) |
| 12 | |
| 13 | // Conflict is a draft that could not commit, and what it is up against: |
| 14 | // the hunks of the block merge, or, with no merge base, the two texts |
| 15 | // side by side (§5). |
| 16 | type Conflict struct { |
| 17 | PageID, Current int64 |
| 18 | Hunks []markup.Hunk |
| 19 | NoBase bool |
| 20 | Mine, Theirs string |
| 21 | Version int64 |
| 22 | } |
| 23 | |
| 24 | // ConflictOf is the viewer's conflict on a page, or ErrNotFound when |
| 25 | // they have no draft there. |
| 26 | func (store *Store) ConflictOf(ctx context.Context, viewer Viewer, |
| 27 | pageID int64) (Conflict, error) { |
| 28 | page, err := store.readable(ctx, viewer, pageID) |
| 29 | if err != nil { |
| 30 | return Conflict{}, err |
| 31 | } |
| 32 | draft, found, err := store.OwnDraft(ctx, viewer, |
| 33 | DraftKey{PageID: pageID}) |
| 34 | if err != nil || !found { |
| 35 | return Conflict{}, errors.Join(ErrNotFound, err) |
| 36 | } |
| 37 | current, err := store.OpenPage(page) |
| 38 | if err != nil { |
| 39 | return Conflict{}, err |
| 40 | } |
| 41 | conflict := Conflict{PageID: pageID, Current: page.Revision, |
| 42 | Mine: draft.Body, Theirs: current.Body, Version: draft.Version} |
| 43 | base, found, err := store.baseBody(ctx, pageID, draft.BaseRevision) |
| 44 | if err != nil { |
| 45 | return conflict, err |
| 46 | } |
| 47 | if !found { |
| 48 | conflict.NoBase = true |
| 49 | return conflict, nil |
| 50 | } |
| 51 | conflict.Hunks, _ = markup.Merge3(base, draft.Body, current.Body) |
| 52 | return conflict, nil |
| 53 | } |
| 54 | |
| 55 | // baseBody is a revision's body, if it is still in the store. |
| 56 | func (store *Store) baseBody(ctx context.Context, pageID, |
| 57 | revision int64) (string, bool, error) { |
| 58 | var row Revision |
| 59 | err := store.database.WithContext(ctx).Where("page_id = ? AND "+ |
| 60 | "revision = ? AND at > ?", pageID, revision, |
| 61 | store.now().UTC().Add(-HistoryWindow)).First(&row).Error |
| 62 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 63 | return "", false, nil |
| 64 | } |
| 65 | if err != nil { |
| 66 | return "", false, err |
| 67 | } |
| 68 | record, err := store.openRecord(seal.PurposeRecord, row.SealedRecord) |
| 69 | return record.Body, true, err |
| 70 | } |
| 71 | |
| 72 | // Conflicts is how many hunks need a choice. |
| 73 | func (conflict Conflict) Conflicts() int { |
| 74 | count := 0 |
| 75 | for _, hunk := range conflict.Hunks { |
| 76 | if hunk.Conflict { |
| 77 | count++ |
| 78 | } |
| 79 | } |
| 80 | return count |
| 81 | } |
| 82 | |