oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package mapa
2
3import (
4 "context"
5 "crypto/rand"
6 "errors"
7
8 "amadan.net/oficina/mapa/internal/mapa/markup"
9)
10
11// ErrNotLinkable is a block that cannot carry a ^id: a code block's text
12// is code, and a rule has none.
13var ErrNotLinkable = errors.New("mapa: that block cannot be linked")
14
15// MarkBlock is "Link to this block" (§3.2): it gives one block of a team
16// page a ^id marker, as an ordinary attributed edit to that page by the
17// person, and returns the marker. A marker is minted only by an edit to
18// the page that holds the block, never from a page that links to it, so
19// nobody's private link ever shows up in a team page's history.
20func (store *Store) MarkBlock(ctx context.Context, who string, pageID int64,
21 number int) (string, error) {
22 var marker string
23 err := store.write(ctx, func(tx *Tx) error {
24 actor, err := tx.member(who)
25 if err != nil {
26 return err
27 }
28 page, record, err := tx.teamPage(actor, pageID)
29 if err != nil {
30 return err
31 }
32 blocks := markup.Parse(record.Body)
33 if number < 0 || number >= len(blocks) {
34 return ErrNotFound
35 }
36 block := blocks[number]
37 if marker = block.Marker; marker != "" {
38 return errNoChange
39 }
40 if block.Kind == markup.Code || block.Kind == markup.Rule ||
41 markup.IsFence(block.Kind) {
42 return ErrNotLinkable
43 }
44 if marker, err = newMarker(); err != nil {
45 return err
46 }
47 record.Body = markup.Replace(record.Body, blocks,
48 map[int]string{number: block.Source + " ^" + marker})
49 return tx.commit(&page, record, actor,
50 linkVerb(page, VerbMarked), attachNothing)
51 })
52 return marker, quiet(err)
53}
54
55// newMarker is a short random ^id: six letters and digits.
56func newMarker() (string, error) {
57 const alphabet = "abcdefghijkmnpqrstuvwxyz23456789"
58 raw := make([]byte, 6)
59 if _, err := rand.Read(raw); err != nil {
60 return "", err
61 }
62 for at, value := range raw {
63 raw[at] = alphabet[int(value)%len(alphabet)]
64 }
65 return string(raw), nil
66}
67