gunk-dev/the-valley

derive.go

source68dab279fa3bmain's published tip history
9.1 KiB
1package knot
2
3import (
4 "fmt"
5 "slices"
6 "sort"
7 "strings"
8 "time"
9)
10
11// Graph is a whole graph, read: every knot, and every comment on each.
12type Graph struct {
13 Index *Index
14 Knots map[string]*Knot
15 Comments map[string][]Noted // by the ID of the knot they are on, oldest first
16
17 // children and blocks are the edges read backwards, built on the
18 // first view.
19 children, blocks map[string][]string
20}
21
22// Noted is one comment as the graph holds it: what it says, its ID and
23// where it is, when it was written, and the operation that wrote it.
24type Noted struct {
25 Comment
26 ID string
27 Path string
28 At time.Time
29 Op string
30}
31
32// Load reads and validates a whole graph.
33func Load(idx *Index, read Reader) (*Graph, error) {
34 if err := Validate(idx, read); err != nil {
35 return nil, err
36 }
37 g := &Graph{Index: idx, Knots: map[string]*Knot{}, Comments: map[string][]Noted{}}
38 for id, f := range idx.Knots {
39 data, err := read(f.OID, MaxKnotSize)
40 if err != nil {
41 return nil, err
42 }
43 if g.Knots[id], err = ParseKnot(f.Path, f.Slug, data); err != nil {
44 return nil, err
45 }
46 }
47 for path, f := range idx.Comments {
48 data, err := read(f.OID, MaxCommentSize)
49 if err != nil {
50 return nil, err
51 }
52 c, err := ParseComment(path, data)
53 if err != nil {
54 return nil, err
55 }
56 at, err := time.Parse(CommentStamp, f.Stamp)
57 if err != nil {
58 return nil, fmt.Errorf("%s: its stamp %s is no time", path, f.Stamp)
59 }
60 g.Comments[f.ID] = append(g.Comments[f.ID], Noted{Comment: *c, ID: f.CommentID(), Path: path, At: at, Op: f.Op})
61 }
62 for _, list := range g.Comments {
63 sort.Slice(list, func(i, j int) bool { return list[i].Path < list[j].Path })
64 }
65 return g, nil
66}
67
68// Empty is the graph a project holds before its first knot.
69func Empty() *Graph {
70 idx, _ := Layout(nil)
71 return &Graph{Index: idx, Knots: map[string]*Knot{}, Comments: map[string][]Noted{}}
72}
73
74// IDs are every knot's ID, sorted.
75func (g *Graph) IDs() []string {
76 ids := make([]string, 0, len(g.Knots))
77 for id := range g.Knots {
78 ids = append(ids, id)
79 }
80 sort.Strings(ids)
81 return ids
82}
83
84// Foreign resolves a reference to another project's knot. found is false
85// when that project's graph holds no such knot; err is for a graph that
86// could not be read.
87type Foreign func(ref string) (k *Knot, found bool, err error)
88
89// View is what the graph says of one knot beyond its own fields: whether
90// it is ready to be worked on, what holds it up, and what it holds up.
91// None of it is stored; it is derived from the graph each time.
92type View struct {
93 // Ready is an outcome or a bug that is active, unclaimed, and every
94 // blocker of which is terminal. An idea is never ready: it is thought
95 // about, not picked up as work. Nor is a question: it is answered.
96 Ready bool `json:"ready"`
97 // WaitingOn are the blockers that are not terminal, or that could not
98 // be resolved.
99 WaitingOn []string `json:"waiting_on"`
100 // ClearedByEnding are blockers that cleared by being abandoned,
101 // discarded, superseded or dropped rather than finished: they no
102 // longer block, as the archive's rule says, but a reader should know.
103 ClearedByEnding []string `json:"cleared_by_ending"`
104 // Dangling are references to another project's knots that its graph
105 // does not hold; Unresolved are those whose graph could not be read.
106 Dangling []string `json:"dangling"`
107 Unresolved []string `json:"unresolved"`
108 // Children are the knots whose parent this is, and Blocks the knots
109 // whose blocked_by names it.
110 Children []string `json:"children"`
111 Blocks []string `json:"blocks"`
112 // Progress is set for a knot with children.
113 Progress *Progress `json:"progress,omitempty"`
114 // Claim is set for a claimed knot.
115 Claim *Claim `json:"claim,omitempty"`
116}
117
118// Progress is a parent's children that are finished, out of its children:
119// terminal children that are not abandoned, out of the children that are
120// not abandoned.
121type Progress struct {
122 Done int `json:"done"`
123 Of int `json:"of"`
124}
125
126// Claim is a knot's claim, with its age.
127type Claim struct {
128 By string `json:"by"`
129 At string `json:"at"`
130 AgeSeconds int64 `json:"age_seconds"`
131 // Stale is a claim older than StaleClaim: the run that made it may
132 // have ended without releasing it.
133 Stale bool `json:"stale"`
134}
135
136// endings are the terminal statuses that end a knot without finishing it.
137var endings = []string{"abandoned", "discarded", "superseded", "dropped"}
138
139// View derives the view of the knot with id at the time now. foreign
140// resolves references to other projects' knots; nil leaves them all
141// unresolved.
142func (g *Graph) View(id string, now time.Time, foreign Foreign) View {
143 k := g.Knots[id]
144 v := View{WaitingOn: []string{}, ClearedByEnding: []string{}, Dangling: []string{}, Unresolved: []string{},
145 Children: []string{}, Blocks: []string{}}
146 for _, ref := range k.BlockedBy {
147 var b *Knot
148 if IsLocalID(ref) {
149 b = g.Knots[ref]
150 } else if foreign == nil {
151 v.Unresolved = append(v.Unresolved, ref)
152 } else if found, ok, err := foreign(ref); err != nil {
153 v.Unresolved = append(v.Unresolved, ref)
154 } else if !ok {
155 v.Dangling = append(v.Dangling, ref)
156 } else {
157 b = found
158 }
159 switch {
160 case b == nil:
161 v.WaitingOn = append(v.WaitingOn, ref)
162 case b.Active():
163 v.WaitingOn = append(v.WaitingOn, ref)
164 case slices.Contains(endings, b.Status):
165 v.ClearedByEnding = append(v.ClearedByEnding, ref)
166 }
167 }
168 if g.children == nil {
169 g.children, g.blocks = map[string][]string{}, map[string][]string{}
170 for _, other := range g.IDs() {
171 o := g.Knots[other]
172 if o.Parent != "" {
173 g.children[o.Parent] = append(g.children[o.Parent], other)
174 }
175 for _, ref := range o.BlockedBy {
176 g.blocks[ref] = append(g.blocks[ref], other)
177 }
178 }
179 }
180 var progress Progress
181 for _, child := range g.children[id] {
182 v.Children = append(v.Children, child)
183 if o := g.Knots[child]; o.Status != "abandoned" {
184 progress.Of++
185 if !o.Active() {
186 progress.Done++
187 }
188 }
189 }
190 v.Blocks = append(v.Blocks, g.blocks[id]...)
191 if len(v.Children) > 0 {
192 v.Progress = &progress
193 }
194 // A claim on a terminal knot is a leftover, and is ignored.
195 claimed := k.ClaimedBy != "" && k.Active()
196 if claimed {
197 c := &Claim{By: k.ClaimedBy, At: k.ClaimedAt}
198 if at, err := time.Parse(time.RFC3339, k.ClaimedAt); err == nil {
199 age := now.Sub(at)
200 c.AgeSeconds = int64(age / time.Second)
201 c.Stale = age > StaleClaim
202 }
203 v.Claim = c
204 }
205 v.Ready = (k.Type == "outcome" || k.Type == "bug") && k.Active() && !claimed && len(v.WaitingOn) == 0
206 return v
207}
208
209// Schema is the model as `valley knot schema` prints it: the types and
210// their statuses, the fields, the edges and the limits, so that a reader
211// of the graph never has to read the CUE schema.
212type Schema struct {
213 Schema string `json:"schema"`
214 Ref string `json:"ref"`
215 Types []Type `json:"types"`
216 Fields []Field `json:"fields"`
217 Edges []Edge `json:"edges"`
218 Limits Limits `json:"limits"`
219}
220
221// Edge is one field that names other knots.
222type Edge struct {
223 Field string `json:"field"`
224 From string `json:"from"`
225 To string `json:"to"`
226 Meaning string `json:"meaning"`
227}
228
229// Limits are the limits a graph is held to.
230type Limits struct {
231 Knots int `json:"knots"`
232 Comments int `json:"comments"`
233 KnotBytes int `json:"knot_bytes"`
234 CommentBytes int `json:"comment_bytes"`
235 ChangedPaths int `json:"changed_paths_per_commit"`
236 TitleBytes int `json:"title_bytes"`
237 ListItems int `json:"list_items"`
238}
239
240// TheSchema is the model.
241func TheSchema() Schema {
242 return Schema{
243 Schema: "valley-knot-schema/v1",
244 Ref: Ref,
245 Types: Types,
246 Fields: Fields,
247 Edges: []Edge{
248 {Field: "parent", From: "any knot", To: "an outcome in this graph",
249 Meaning: "the knot belongs to the outcome; parent edges form no cycle"},
250 {Field: "blocked_by", From: "outcome, bug", To: "any knot in this graph, or <project>:<id> in another",
251 Meaning: "the knot waits on each until it is terminal; blocked_by edges form no cycle"},
252 {Field: "graduated_into", From: "a graduated idea", To: "an outcome or a question in this graph",
253 Meaning: "where the idea moved: work taken on, or a question to settle"},
254 },
255 Limits: Limits{Knots: MaxKnots, Comments: MaxComments, KnotBytes: MaxKnotSize,
256 CommentBytes: MaxCommentSize, ChangedPaths: MaxChangedPaths, TitleBytes: MaxTitle, ListItems: MaxListItems},
257 }
258}
259
260// Describe is the schema as text, for a terminal.
261func Describe() string {
262 var b strings.Builder
263 fmt.Fprintf(&b, "knots live at %s, one file each; comments at comments/<id>/.\n\ntypes:\n", Ref)
264 for _, t := range Types {
265 fmt.Fprintf(&b, " %-9s %s-<7 hex> in %s/\n", t.Name, t.Prefix, t.Directory)
266 fmt.Fprintf(&b, " active: %s terminal: %s\n", strings.Join(t.Active, ", "), strings.Join(t.Terminal, ", "))
267 }
268 b.WriteString("\nfields:\n")
269 for _, f := range Fields {
270 fmt.Fprintf(&b, " %-15s on %s; %s\n", f.Name, strings.Join(f.On, ", "), f.Meaning)
271 }
272 b.WriteString("\nedges:\n")
273 for _, e := range TheSchema().Edges {
274 fmt.Fprintf(&b, " %-15s %s → %s: %s\n", e.Field, e.From, e.To, e.Meaning)
275 }
276 fmt.Fprintf(&b, "\nlimits: %d knots, %d comments, %d bytes a knot, %d a comment, %d files a commit\n",
277 MaxKnots, MaxComments, MaxKnotSize, MaxCommentSize, MaxChangedPaths)
278 return b.String()
279}