gunk-dev/the-valley

derive.go

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