Skip to content
quarry Artifact [f032cc36fd]
Login

Artifact [f032cc36fd]

Artifact f032cc36fd527a020c09a6cd19dbdc686aba3288b923642b0c64a93c0f975cd7:


package index

import (
	"sort"
	"strings"
	"time"
	"unicode/utf8"
)

// A BLOCKING COMMENT is a landing remark whose text opens with
// "blocking:". It holds the landing's accept until it is settled, and it
// is settled by a later reply in the same thread whose first line names
// it:
//
//	resolved: 8a0ba3d4805e
//	reopened: 8a0ba3d4805e
//
// All three are ordinary forum posts, so a stock Fossil clone carries and
// shows them and quarry derives every open blocker from history alone;
// nothing about one lives anywhere else. The marker is read from the
// post's PROSE: after a line note's header when it has one, so a blocking
// note on a line and a blocking remark on the whole diff share one
// dialect.

// MarkerKind is what a remark's first line declares.
type MarkerKind string

const (
	MarkNone     MarkerKind = ""
	MarkBlocking MarkerKind = "blocking"
	MarkResolved MarkerKind = "resolved"
	MarkReopened MarkerKind = "reopened"
)

// MinMarkerHash is the shortest post-hash prefix a resolve or reopen may
// name: short enough to type, long enough that a thread cannot hold two.
const MinMarkerHash = 10

// Marker is a parsed first line. Hash is the lowercase target prefix of a
// resolve or reopen and empty for every other kind.
type Marker struct {
	Kind MarkerKind
	Hash string
}

// ParseMarker reads the marker a remark's prose opens with. It is the one
// reader and, through FormatMarker and BlockingText, the one writer's
// partner: a post the API writes and a post a clone synced in are read by
// the same lines.
func ParseMarker(prose string) Marker {
	s := strings.TrimLeft(prose, " \t\r\n")
	if hasFold(s, "blocking:") {
		return Marker{Kind: MarkBlocking}
	}
	for _, k := range []MarkerKind{MarkResolved, MarkReopened} {
		if !hasFold(s, string(k)+":") {
			continue
		}
		first, _, _ := strings.Cut(s[len(k)+1:], "\n")
		h := strings.ToLower(strings.TrimSpace(first))
		if len(h) < MinMarkerHash || len(h) > 64 || strings.Trim(h, "0123456789abcdef") != "" {
			return Marker{}
		}
		return Marker{Kind: k, Hash: h}
	}
	return Marker{}
}

// hasFold is strings.HasPrefix ignoring ASCII case.
func hasFold(s, prefix string) bool {
	return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
}

// BlockingText is a blocking remark's text with the marker and the
// spaces after it removed.
func BlockingText(prose string) string {
	s := strings.TrimLeft(prose, " \t\r\n")
	if !hasFold(s, "blocking:") {
		return prose
	}
	return strings.TrimLeft(s[len("blocking:"):], " \t")
}

// AsBlocking writes text as a blocking remark: it opens with the marker,
// which it adds unless the text already has it.
func AsBlocking(text string) string {
	if ParseMarker(text).Kind == MarkBlocking {
		return text
	}
	return "blocking: " + text
}

// FormatMarker writes a resolve or reopen: the marker line, then the
// author's own words under a blank line when there are any.
func FormatMarker(kind MarkerKind, hash, text string) string {
	line := string(kind) + ": " + hash
	if strings.TrimSpace(text) == "" {
		return line
	}
	return line + "\n\n" + text
}

// BlockingNote is one blocking comment, for a page or a refusal to name.
type BlockingNote struct {
	// Hash is the newest version of the comment: what a resolve written
	// now names. Any older version's hash still finds it (Chain).
	Hash string `json:"hash"`
	User string `json:"user"`
	Date string `json:"date"`
	// File and Line say where a blocking LINE NOTE points; empty and 0
	// for a remark on the whole diff.
	File string `json:"file,omitempty"`
	Line int    `json:"line,omitempty"`
	// Text is the first line of what was said, after the marker.
	Text string `json:"text"`
	// Chain is every version's hash, oldest first.
	Chain []string `json:"-"`
}

// blockingTextMax bounds Text: it is a pointer back to the post, not the post.
const blockingTextMax = 200

// Provenance says who wrote one artifact and when this forge first had
// it, as the forge recorded it when the artifact arrived. ok is false
// when it recorded nothing. The artifact's own user and date are claims
// any clone can make; this is not, and it is all a settlement is judged
// by. received also bounds a version's date, since a client picks that
// too.
type Provenance func(hash string) (writer string, received time.Time, ok bool)

// Blocking is every blocking comment of a landing's thread, and the ones
// among them still open, each oldest first. chains is the thread's posts
// with their edit chains (ForumThreadChains), each oldest version first.
//
// A post is a blocker if ANY version of it opened with the marker, and
// stays one unless the version that dropped it was written by someone
// who may settle it: an edit by a moderator or a stranger neither
// settles nor hides a blocking comment. Hiding a post is display only
// and changes nothing here.
//
// A blocker is open unless the NEWEST resolve or reopen aimed at it is a
// resolve, and the two are not symmetric. Anyone who can comment can
// already start a new blocker, so a reopen grants nobody anything: it
// counts from ANY version of its post, whoever wrote it and whether or
// not the forge recorded a writer, which is why no edit and no deleted
// account can take one away. A resolve is the act that lets a landing
// through, so it counts only from the newest version of its post written
// by someone who may settle the blocker (mayAct, judged on prov, never
// on the user the artifact claims); versions after it by anyone else are
// ignored, not disqualifying, and one by a settler that no longer says
// it takes it back.
//
// Newest is by the time the version was written, capped at when this
// forge received it, ties by hash, so a client's clock cannot put a
// resolve ahead of a later reopen. A reopen with no receive time sorts
// last. Either marker names any version of the blocker, so fixing a typo
// does not reopen it.
//
// Only a plain remark counts: a state, retarget or update reply carries an
// event whose message is not a review comment. The opener needs no rule of
// its own, since its header means its prose never opens with a marker.
func Blocking(chains [][]ForumPost, prov Provenance, mayAct func(actor, blockAuthor string) bool) (all, open []BlockingNote) {
	type blocker struct {
		note   BlockingNote
		author string
	}
	type act struct {
		kind   MarkerKind
		target string
		hash   string
		at     time.Time
	}
	var blockers []blocker
	var remarks [][]ForumPost
	for _, versions := range chains {
		if len(versions) == 0 {
			continue
		}
		// The author is whoever the forge recorded as writing the first
		// version; the name it claims only when none is recorded.
		author := versions[0].User
		if who, _, ok := prov(versions[0].Hash); ok {
			author = who
		}
		var held *BlockingNote
		for _, v := range versions {
			prose, note, plain := remarkProse(v.Body)
			switch {
			case plain && ParseMarker(prose).Kind == MarkBlocking:
				n := BlockingNote{Hash: v.Hash, User: author, Date: versions[0].Date,
					File: note.File, Line: note.Line, Text: blockingLine(BlockingText(prose))}
				held = &n
			case held != nil:
				// This version dropped the marker: only someone who may
				// settle the comment can take it away this way.
				if who, _, ok := prov(v.Hash); ok && mayAct(who, author) {
					held = nil
				}
			}
		}
		if held == nil {
			remarks = append(remarks, versions)
			continue
		}
		held.Hash = versions[len(versions)-1].Hash
		held.Chain = make([]string, len(versions))
		for i, v := range versions {
			held.Chain[i] = v.Hash
		}
		blockers = append(blockers, blocker{*held, author})
	}
	// find is the one blocker a prefix names; a prefix naming two posts
	// names neither.
	find := func(prefix string) *blocker {
		var found *blocker
		for i := range blockers {
			for _, h := range blockers[i].note.Chain {
				if strings.HasPrefix(h, prefix) {
					if found != nil && found != &blockers[i] {
						return nil
					}
					found = &blockers[i]
					break
				}
			}
		}
		return found
	}
	// when is a version's time: its date, capped at the forge's receipt.
	// A version the forge has no receipt for is last of all.
	never := time.Date(9999, 1, 1, 0, 0, 0, 0, time.UTC)
	when := func(v ForumPost) time.Time {
		_, received, ok := prov(v.Hash)
		if !ok {
			return never
		}
		at, err := time.Parse("2006-01-02T15:04:05.999999999", v.Date)
		if err != nil || received.Before(at) {
			return received
		}
		return at
	}
	var acts []act
	for _, versions := range remarks {
		var resolve *act
		var resolved *blocker
		for _, v := range versions {
			prose, _, plain := remarkProse(v.Body)
			if !plain {
				continue
			}
			m := ParseMarker(prose)
			if m.Kind == MarkReopened {
				acts = append(acts, act{MarkReopened, m.Hash, v.Hash, when(v)})
			}
			who, _, ok := prov(v.Hash)
			if !ok {
				continue // a version nobody can be traced to is no settler's
			}
			if m.Kind == MarkResolved {
				if t := find(m.Hash); t != nil && mayAct(who, t.author) {
					resolve, resolved = &act{MarkResolved, m.Hash, v.Hash, when(v)}, t
					continue
				}
			}
			if resolved != nil && mayAct(who, resolved.author) {
				resolve, resolved = nil, nil
			}
		}
		if resolve != nil {
			acts = append(acts, *resolve)
		}
	}
	sort.SliceStable(acts, func(i, j int) bool {
		if !acts[i].at.Equal(acts[j].at) {
			return acts[i].at.Before(acts[j].at)
		}
		return acts[i].hash < acts[j].hash
	})
	settled := map[string]bool{}
	for _, a := range acts {
		if t := find(a.target); t != nil {
			settled[t.note.Hash] = a.kind == MarkResolved
		}
	}
	sort.SliceStable(blockers, func(i, j int) bool {
		if blockers[i].note.Date != blockers[j].note.Date {
			return blockers[i].note.Date < blockers[j].note.Date
		}
		return blockers[i].note.Hash < blockers[j].note.Hash
	})
	for _, b := range blockers {
		all = append(all, b.note)
		if !settled[b.note.Hash] {
			open = append(open, b.note)
		}
	}
	return all, open
}

// OpenBlocking is Blocking's open comments alone.
func OpenBlocking(chains [][]ForumPost, prov Provenance, mayAct func(actor, blockAuthor string) bool) []BlockingNote {
	_, open := Blocking(chains, prov, mayAct)
	return open
}

// ChainOf finds the post any version of which has this hash prefix.
// ambiguous is true when the prefix names versions of more than one post.
func ChainOf(chains [][]ForumPost, prefix string) (chain []ForumPost, ok, ambiguous bool) {
	for _, c := range chains {
		for _, v := range c {
			if prefix != "" && strings.HasPrefix(v.Hash, prefix) {
				if ok {
					return nil, false, true
				}
				chain, ok = c, true
				break
			}
		}
	}
	return chain, ok, false
}

// remarkProse is a post body's prose, after a line note's header when it
// has one, and plain: false for the replies that record an event.
func remarkProse(body string) (prose string, note LineNote, plain bool) {
	if _, ev := LandingTransition(body); ev || isRetarget(body) || isUpdate(body) {
		return "", LineNote{}, false
	}
	if n, rest, ok := ParseLineNote(body); ok {
		return rest, n, true
	}
	return body, LineNote{}, true
}

func isRetarget(body string) bool { _, ok := parseLandingTarget(body); return ok }
func isUpdate(body string) bool   { _, ok := LandingUpdate(body); return ok }

// blockingLine is the first non-empty line of s, cut to blockingTextMax runes.
func blockingLine(s string) string {
	for _, l := range strings.Split(s, "\n") {
		if l = strings.TrimSpace(l); l != "" {
			if utf8.RuneCountInString(l) > blockingTextMax {
				return string([]rune(l)[:blockingTextMax]) + "..."
			}
			return l
		}
	}
	return ""
}