gunk-dev/the-valley

knot.go

source3c691633b1e7main's published tip history
40.1 KiB
1// valley knot: the plan graph's API. A project's plan is a graph of
2// knots at refs/the-valley/knots on origin (the knot module), and these
3// verbs read it and write it without a checkout and without review: each
4// write is one commit on the ref, built with git plumbing on a private
5// index and pushed with a lease on the tip it was built on.
6//
7// When the lease fails, the operation is formed again on the new tip and
8// pushed again, at most knot.Attempts times in all, after a random pause.
9// set, edit, link --parent, claim and unclaim are compare-and-set: each
10// remembers the value of every field it changes as it first read it, and
11// when a retry finds another value there it reports a conflict instead of
12// overwriting it. set's --force skips that comparison. --if adds a
13// comparison of its own, on a field the knot module names, which holds on
14// every try. Every operation carries a Valley-Op trailer naming an ID
15// chosen once, so after a push whose outcome it cannot tell, the verb
16// looks for the ID among the ref's latest commits before it tries again,
17// and an operation is never recorded twice.
18
19package main
20
21import (
22 "bufio"
23 "bytes"
24 "crypto/rand"
25 "encoding/hex"
26 "encoding/json"
27 "errors"
28 "fmt"
29 "io"
30 mrand "math/rand/v2"
31 "os"
32 "os/exec"
33 "path/filepath"
34 "slices"
35 "sort"
36 "strconv"
37 "strings"
38 "time"
39 "unicode"
40
41 "the-valley/knot"
42)
43
44const knotUsage = `usage: valley knot <verb> [args]
45
46 new <type> <title> [--parent ID] [--blocked-by ID]... [--owner P] [--target PROJECT] [--body -]
47 show <id> [--json]
48 list [--type T] [--status S] [--owner P] [--ready] [--json]
49 set <id> <field>=<value>... [--if <field>=<value>]... [--force]
50 link <id> (--blocked-by ID | --parent ID | --change LINK)...
51 unlink <id> (--blocked-by ID | --parent ID | --change LINK)...
52 edit <id> --body -
53 comment <id> (-m TEXT | --body -)
54 claim <id> --run RUN
55 unclaim <id>
56 schema [--json]
57
58every verb takes --project NAME and --json. exit status 3 is a conflict.`
59
60// conflict is a write refused because the graph no longer holds what the
61// operation was formed on, or what --if requires. Exit status 3.
62type conflict string
63
64func (c conflict) Error() string { return string(c) }
65
66// unchanged is a write that would change nothing: it is not pushed.
67type unchanged string
68
69func (u unchanged) Error() string { return string(u) }
70
71// knotArgs are a knot verb's arguments.
72type knotArgs struct {
73 verb string
74 pos []string
75 project string
76 json, ready, force, stdin bool
77 parent, owner, target string
78 typ, status, run, message string
79 blockedBy, changes []string
80 ifs []string
81 hasParent, hasMessage bool
82}
83
84// knotFlags are the flags each verb takes, beyond --project and --json.
85var knotFlags = map[string][]string{
86 "new": {"--parent", "--blocked-by", "--owner", "--target", "--body"},
87 "show": {},
88 "list": {"--type", "--status", "--owner", "--ready"},
89 "set": {"--if", "--force"},
90 "link": {"--blocked-by", "--parent", "--change", "--if"},
91 "unlink": {"--blocked-by", "--parent", "--change", "--if"},
92 "edit": {"--body", "--if"},
93 "comment": {"-m", "--body"},
94 "claim": {"--run", "--if"},
95 "unclaim": {"--if"},
96 "schema": {},
97}
98
99// knotPositionals is how many positional arguments each verb takes: at
100// least the first, at most the second (-1 for any number).
101var knotPositionals = map[string][2]int{
102 "new": {2, 2}, "show": {1, 1}, "list": {0, 0}, "set": {2, -1}, "link": {1, 1}, "unlink": {1, 1},
103 "edit": {1, 1}, "comment": {1, 1}, "claim": {1, 1}, "unclaim": {1, 1}, "schema": {0, 0},
104}
105
106func parseKnotArgs(args []string) (knotArgs, error) {
107 var a knotArgs
108 if len(args) == 0 {
109 return a, failure(knotUsage)
110 }
111 a.verb, args = args[0], args[1:]
112 allowed, ok := knotFlags[a.verb]
113 if !ok {
114 return a, failure(fmt.Sprintf("knot has no verb %q; its verbs are new, show, list, set, link, unlink, edit, comment, claim, unclaim and schema\n%s", a.verb, knotUsage))
115 }
116 for i := 0; i < len(args); i++ {
117 arg := args[i]
118 flag, inline, hasInline := strings.Cut(arg, "=")
119 if !strings.HasPrefix(arg, "-") || arg == "-" {
120 a.pos = append(a.pos, arg)
121 continue
122 }
123 if arg == "--" {
124 a.pos = append(a.pos, args[i+1:]...)
125 break
126 }
127 if !hasInline {
128 flag = arg
129 }
130 if flag != "--project" && flag != "--json" && !slices.Contains(allowed, flag) {
131 return a, failure(fmt.Sprintf("knot %s takes no %s; it takes %s", a.verb, flag, strings.Join(append([]string{"--project", "--json"}, allowed...), ", ")))
132 }
133 value := func() (string, error) {
134 if hasInline {
135 return inline, nil
136 }
137 if i+1 >= len(args) {
138 return "", failure(flag + " needs a value")
139 }
140 i++
141 return args[i], nil
142 }
143 var v string
144 var err error
145 switch flag {
146 case "--json", "--ready", "--force":
147 if hasInline {
148 return a, failure(flag + " takes no value")
149 }
150 switch flag {
151 case "--json":
152 a.json = true
153 case "--ready":
154 a.ready = true
155 default:
156 a.force = true
157 }
158 continue
159 }
160 if v, err = value(); err != nil {
161 return a, err
162 }
163 switch flag {
164 case "--project":
165 a.project = v
166 case "--parent":
167 a.parent, a.hasParent = v, true
168 case "--blocked-by":
169 a.blockedBy = append(a.blockedBy, v)
170 case "--change":
171 a.changes = append(a.changes, v)
172 case "--owner":
173 a.owner = v
174 case "--target":
175 a.target = v
176 case "--type":
177 a.typ = v
178 case "--status":
179 a.status = v
180 case "--run":
181 a.run = v
182 case "--if":
183 a.ifs = append(a.ifs, v)
184 case "-m":
185 a.message, a.hasMessage = v, true
186 case "--body":
187 if v != "-" {
188 return a, failure("--body takes -, and reads the body from stdin")
189 }
190 a.stdin = true
191 }
192 }
193 n := knotPositionals[a.verb]
194 if len(a.pos) < n[0] || (n[1] >= 0 && len(a.pos) > n[1]) {
195 return a, failure(fmt.Sprintf("knot %s takes %s\n%s", a.verb, positionalsOf(a.verb), knotUsage))
196 }
197 return a, nil
198}
199
200func positionalsOf(verb string) string {
201 switch verb {
202 case "new":
203 return "a type and a title"
204 case "set":
205 return "a knot's id and one or more <field>=<value>"
206 case "list", "schema":
207 return "no argument but its flags"
208 }
209 return "a knot's id"
210}
211
212// runKnot runs one knot verb and returns its exit status.
213func runKnot(g git, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
214 a, err := parseKnotArgs(args)
215 if err != nil {
216 fmt.Fprintf(stderr, "valley: %s\n", err)
217 return 2
218 }
219 err = knotVerb(g, a, stdin, stdout)
220 var c conflict
221 var u unchanged
222 switch {
223 case err == nil:
224 return 0
225 case errors.As(err, &u):
226 fmt.Fprintf(stderr, "valley: %s\n", u)
227 return 0
228 case errors.As(err, &c):
229 fmt.Fprintf(stderr, "valley: conflict: %s\n", c)
230 return 3
231 }
232 fmt.Fprintf(stderr, "valley: %s\n", err)
233 return 1
234}
235
236func knotVerb(g git, a knotArgs, stdin io.Reader, stdout io.Writer) error {
237 if a.verb == "schema" {
238 if a.json {
239 return writeKnotJSON(stdout, knot.TheSchema())
240 }
241 _, err := io.WriteString(stdout, knot.Describe())
242 return err
243 }
244 if !g.succeeds(true, "rev-parse", "--git-dir") {
245 return failure("not a git repository")
246 }
247 if a.verb == "show" && knot.IsQualifiedID(a.pos[0]) {
248 project, id, _ := strings.Cut(a.pos[0], ":")
249 if a.project != "" && a.project != project {
250 return failure(fmt.Sprintf("%s names a knot in %s, and --project names %s", a.pos[0], project, a.project))
251 }
252 a.project, a.pos[0] = project, id
253 }
254 r, err := knotRemote(g, a.project)
255 if err != nil {
256 return err
257 }
258 switch a.verb {
259 case "show":
260 return knotShow(r, a, stdout)
261 case "list":
262 return knotList(r, a, stdout)
263 }
264 var body string
265 if a.stdin {
266 data, err := io.ReadAll(io.LimitReader(stdin, knot.MaxKnotSize+1))
267 if err != nil {
268 return failure("could not read the body from stdin")
269 }
270 body = knot.NormalBody(string(data))
271 }
272 principal, err := g.output(true, "config", "valley.principal")
273 if err != nil || !knot.IsName(principal) {
274 return failure("a knot's writes name the principal your key pushes as, and git config valley.principal names none; set it with git config valley.principal <name>")
275 }
276 o, err := formOp(a, body, principal)
277 if err != nil {
278 return err
279 }
280 return r.write(g, o, principal, a.json, stdout)
281}
282
283// knotRemote is where a project's graph is read and written: the current
284// repository's origin, or, for another project, a clone kept under the
285// cache directory whose origin is the project's URL. That URL is origin's
286// with its last path segment replaced by the project's name, as changes
287// --all derives a project's URL from the instance's.
288func knotRemote(g git, name string) (remote, error) {
289 here := project(g)
290 if name == "" || name == here {
291 return remote{g: g, name: here}, nil
292 }
293 if !knot.IsName(name) {
294 return remote{}, failure(fmt.Sprintf("%q is not a project's name", name))
295 }
296 originURL, err := g.output(true, "remote", "get-url", "origin")
297 if err != nil {
298 return remote{}, failure("this repository has no origin, so no other project can be found beside it")
299 }
300 url, err := projectURL(originURL, name)
301 if err != nil {
302 return remote{}, failure(err.Error())
303 }
304 c, err := cacheRepo(g.restricted(), url, name)
305 if err != nil {
306 return remote{}, failure(err.Error())
307 }
308 return remote{g: c, name: name}, nil
309}
310
311// remote is one project's graph on its origin, and the repository its
312// objects are read and written in.
313type remote struct {
314 g git
315 name string
316}
317
318// knotState is a graph as read at one tip of the ref.
319type knotState struct {
320 tip string // "" before the ref's first commit
321 graph *knot.Graph
322 blobs map[string][]byte // every file's content, by object
323}
324
325func (s knotState) read(oid string, max int) ([]byte, error) {
326 data, ok := s.blobs[oid]
327 if !ok {
328 return nil, errors.New("names an object that was not read")
329 }
330 if len(data) > max {
331 return nil, fmt.Errorf("is %d bytes, more than the %d it may be", len(data), max)
332 }
333 return data, nil
334}
335
336// read reads the graph at origin's tip of the ref: one ls-remote, a fetch
337// of the tip when it is not here, one listing of its tree, and one batched
338// read of every file in it.
339func (r remote) read() (knotState, error) {
340 tip, err := remoteRef(r.g, "origin", knot.Ref)
341 if err != nil {
342 return knotState{}, failure("could not read origin")
343 }
344 if tip == "" {
345 return knotState{graph: knot.Empty(), blobs: map[string][]byte{}}, nil
346 }
347 if err := fetch(r.g, tip); err != nil {
348 return knotState{}, err
349 }
350 return r.readAt(tip)
351}
352
353func (r remote) readAt(commit string) (knotState, error) {
354 entries, err := r.listing(commit)
355 if err != nil {
356 return knotState{}, err
357 }
358 idx, err := knot.Layout(entries)
359 if err != nil {
360 return knotState{}, failure(fmt.Sprintf("the graph at %s does not read: %v", short(commit), err))
361 }
362 var oids []string
363 for _, oid := range idx.Files {
364 oids = append(oids, oid)
365 }
366 blobs, err := r.blobs(oids)
367 if err != nil {
368 return knotState{}, err
369 }
370 s := knotState{tip: commit, blobs: blobs}
371 if s.graph, err = knot.Load(idx, s.read); err != nil {
372 return knotState{}, failure(fmt.Sprintf("the graph at %s does not read: %v", short(commit), err))
373 }
374 return s, nil
375}
376
377// listing lists every tree and file in the commit's tree.
378func (r remote) listing(treeish string) ([]knot.Entry, error) {
379 out, err := r.g.output(true, "ls-tree", "-r", "-t", "-z", "--full-tree", treeish)
380 if err != nil {
381 return nil, failure("could not list the graph's tree at " + short(treeish))
382 }
383 var entries []knot.Entry
384 for _, rec := range strings.Split(out, "\x00") {
385 if rec == "" {
386 continue
387 }
388 meta, path, ok := strings.Cut(rec, "\t")
389 fields := strings.Fields(meta)
390 if !ok || len(fields) != 3 {
391 return nil, failure("git listed the graph's tree in a form this does not read: " + rec)
392 }
393 entries = append(entries, knot.Entry{Path: path, Mode: strings.TrimPrefix(fields[0], "0"), OID: fields[2]})
394 }
395 return entries, nil
396}
397
398// blobs reads every object named, in one cat-file --batch.
399func (r remote) blobs(oids []string) (map[string][]byte, error) {
400 found := map[string][]byte{}
401 if len(oids) == 0 {
402 return found, nil
403 }
404 cmd := exec.Command("git", "cat-file", "--batch")
405 cmd.Env, cmd.Dir = r.g.env, r.g.dir
406 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
407 out, err := cmd.StdoutPipe()
408 if err != nil {
409 return nil, err
410 }
411 if err := cmd.Start(); err != nil {
412 return nil, failure("could not read the graph's files")
413 }
414 in := bufio.NewReader(out)
415 for range oids {
416 header, err := in.ReadString('\n')
417 fields := strings.Fields(header)
418 if err != nil || len(fields) != 3 {
419 _ = cmd.Wait()
420 return nil, failure("could not read the graph's files: git answered " + strconv.Quote(header))
421 }
422 size, err := strconv.Atoi(fields[2])
423 if err != nil || size > knot.MaxKnotSize {
424 _ = cmd.Wait()
425 return nil, failure(fmt.Sprintf("the graph's file %s is larger than any knot", fields[0]))
426 }
427 data := make([]byte, size+1)
428 if _, err := io.ReadFull(in, data); err != nil {
429 _ = cmd.Wait()
430 return nil, failure("could not read the graph's files")
431 }
432 found[fields[0]] = data[:size]
433 }
434 if err := cmd.Wait(); err != nil {
435 return nil, failure("could not read the graph's files")
436 }
437 return found, nil
438}
439
440// op is one write: its ID, and how it is formed on a knotState of the
441// graph. form returns the files it adds or changes, and the commit's
442// subject, or a conflict, or unchanged.
443type op struct {
444 id string
445 form func(s knotState) (files map[string][]byte, subject, id string, err error)
446}
447
448func newOpID() string {
449 var b [8]byte
450 if _, err := rand.Read(b[:]); err != nil {
451 panic(err)
452 }
453 return hex.EncodeToString(b[:])
454}
455
456// formOp turns a verb's arguments into the operation it writes.
457func formOp(a knotArgs, body, principal string) (op, error) {
458 o := op{id: newOpID()}
459 now := clock()
460 guards, err := parseAssignments(a.ifs, "--if")
461 if err != nil {
462 return o, err
463 }
464 for _, g := range guards {
465 if _, ok := knot.FieldNamed(g.field); !ok {
466 return o, failure(fmt.Sprintf("a knot has no field %s; --if compares %s", g.field, strings.Join(fieldNames(), ", ")))
467 }
468 }
469 // first holds the values a compare-and-set read on its first try.
470 var first map[string]string
471 guarded := func(s knotState, id string, fields []string, compare bool) (*knot.Knot, error) {
472 k, ok := s.graph.Knots[id]
473 if !ok {
474 return nil, failure(fmt.Sprintf("the graph holds no knot %s", id))
475 }
476 for _, g := range guards {
477 if got := k.Get(g.field); got != g.value {
478 return nil, conflict(fmt.Sprintf("%s's %s is %q, and --if requires %q", id, g.field, got, g.value))
479 }
480 }
481 if first == nil {
482 first = map[string]string{}
483 for _, f := range fields {
484 first[f] = k.Get(f)
485 }
486 } else if compare {
487 for _, f := range fields {
488 if got := k.Get(f); got != first[f] {
489 return nil, conflict(fmt.Sprintf("%s's %s changed from %q to %q while this was written; read it again, or pass --force to set it anyway", id, f, first[f], got))
490 }
491 }
492 }
493 return k.Clone(), nil
494 }
495 put := func(k *knot.Knot) map[string][]byte {
496 return map[string][]byte{k.Path(): knot.Render(k)}
497 }
498
499 switch a.verb {
500 case "new":
501 t, ok := knot.TypeNamed(a.pos[0])
502 if !ok {
503 return o, failure(fmt.Sprintf("%q is no type of knot; the types are %s", a.pos[0], strings.Join(knot.TypeNames(), ", ")))
504 }
505 if strings.TrimSpace(a.pos[1]) == "" {
506 return o, failure("a knot needs a title")
507 }
508 o.form = func(s knotState) (map[string][]byte, string, string, error) {
509 id, slug := knot.NewID(t, a.pos[1], func(id string) bool { _, ok := s.graph.Index.Knots[id]; return ok })
510 k := &knot.Knot{Type: t.Name, ID: id, Slug: slug, Status: t.Initial(), Title: a.pos[1],
511 Created: now.Format("2006-01-02"), CreatedBy: principal, Parent: a.parent, Owner: a.owner,
512 Target: a.target, Body: body}
513 if t.Name == "outcome" || t.Name == "bug" {
514 k.BlockedBy = sortedSet(a.blockedBy)
515 } else if len(a.blockedBy) > 0 || a.target != "" {
516 return nil, "", "", failure(fmt.Sprintf("a%s %s carries no blocked_by or target; outcomes and bugs do", article(t.Name), t.Name))
517 }
518 return put(k), fmt.Sprintf("knot new %s: %s", id, a.pos[1]), id, nil
519 }
520
521 case "set":
522 id := a.pos[0]
523 sets, err := parseAssignments(a.pos[1:], "set")
524 if err != nil {
525 return o, err
526 }
527 var fields []string
528 for _, s := range sets {
529 f, ok := knot.FieldNamed(s.field)
530 switch {
531 case !ok:
532 return o, failure(fmt.Sprintf("a knot has no field %s; set changes %s", s.field, strings.Join(settable(), ", ")))
533 case f.Set == "link":
534 return o, failure(fmt.Sprintf("%s is an edge; change it with valley knot link or unlink", s.field))
535 case f.Set == "claim":
536 return o, failure(fmt.Sprintf("%s is a claim's; change it with valley knot claim or unclaim", s.field))
537 case f.Set != "set":
538 return o, failure(fmt.Sprintf("%s never changes once a knot is made; set changes %s", s.field, strings.Join(settable(), ", ")))
539 }
540 fields = append(fields, s.field)
541 }
542 o.form = func(s knotState) (map[string][]byte, string, string, error) {
543 k, err := guarded(s, id, fields, !a.force)
544 if err != nil {
545 return nil, "", "", err
546 }
547 before := string(knot.Render(k))
548 for _, a := range sets {
549 setField(k, a.field, a.value)
550 }
551 if string(knot.Render(k)) == before {
552 return nil, "", "", unchanged(fmt.Sprintf("%s already holds that; nothing to change", id))
553 }
554 return put(k), fmt.Sprintf("knot set %s: %s", id, strings.Join(a.pos[1:], " ")), id, nil
555 }
556
557 case "link", "unlink":
558 id := a.pos[0]
559 if len(a.blockedBy) == 0 && !a.hasParent && len(a.changes) == 0 {
560 return o, failure(fmt.Sprintf("knot %s takes --blocked-by, --parent or --change", a.verb))
561 }
562 o.form = func(s knotState) (map[string][]byte, string, string, error) {
563 var fields []string
564 if a.hasParent {
565 fields = []string{"parent"}
566 }
567 k, err := guarded(s, id, fields, true)
568 if err != nil {
569 return nil, "", "", err
570 }
571 before := string(knot.Render(k))
572 var did []string
573 if a.verb == "link" {
574 if a.hasParent {
575 if k.Parent != "" && k.Parent != a.parent {
576 return nil, "", "", conflict(fmt.Sprintf("%s's parent is %s; unlink it first to give it another", id, k.Parent))
577 }
578 k.Parent = a.parent
579 did = append(did, "parent "+a.parent)
580 }
581 if len(a.blockedBy) > 0 {
582 k.BlockedBy = sortedSet(append(slices.Clone(k.BlockedBy), a.blockedBy...))
583 did = append(did, "blocked by "+strings.Join(a.blockedBy, ", "))
584 }
585 if len(a.changes) > 0 {
586 k.Changes = sortedSet(append(slices.Clone(k.Changes), a.changes...))
587 did = append(did, "change "+strings.Join(a.changes, ", "))
588 }
589 } else {
590 if a.hasParent {
591 if k.Parent != a.parent {
592 return nil, "", "", conflict(fmt.Sprintf("%s's parent is %q, not %s", id, k.Parent, a.parent))
593 }
594 k.Parent = ""
595 did = append(did, "parent "+a.parent)
596 }
597 if len(a.blockedBy) > 0 {
598 k.BlockedBy = without(k.BlockedBy, a.blockedBy)
599 if k.BlockedBy == nil && (k.Type == "outcome" || k.Type == "bug") {
600 k.BlockedBy = []string{}
601 }
602 did = append(did, "blocked by "+strings.Join(a.blockedBy, ", "))
603 }
604 if len(a.changes) > 0 {
605 k.Changes = without(k.Changes, a.changes)
606 did = append(did, "change "+strings.Join(a.changes, ", "))
607 }
608 }
609 if string(knot.Render(k)) == before {
610 return nil, "", "", unchanged(fmt.Sprintf("%s already holds that; nothing to change", id))
611 }
612 return put(k), fmt.Sprintf("knot %s %s: %s", a.verb, id, strings.Join(did, "; ")), id, nil
613 }
614
615 case "edit":
616 id := a.pos[0]
617 if !a.stdin {
618 return o, failure("knot edit takes --body -, and reads the new body from stdin")
619 }
620 o.form = func(s knotState) (map[string][]byte, string, string, error) {
621 k, err := guarded(s, id, nil, true)
622 if err != nil {
623 return nil, "", "", err
624 }
625 if first["body"] == "" {
626 first["body"] = "read:" + k.Body
627 } else if first["body"] != "read:"+k.Body {
628 return nil, "", "", conflict(fmt.Sprintf("%s's body changed while this was written; read it again", id))
629 }
630 if k.Body == body {
631 return nil, "", "", unchanged(fmt.Sprintf("%s's body is that already; nothing to change", id))
632 }
633 k.Body = body
634 return put(k), fmt.Sprintf("knot edit %s", id), id, nil
635 }
636
637 case "comment":
638 id := a.pos[0]
639 text := body
640 if a.hasMessage {
641 if a.stdin {
642 return o, failure("knot comment takes -m or --body -, not both")
643 }
644 text = knot.NormalBody(a.message)
645 }
646 if text == "" {
647 return o, failure("knot comment takes the comment, with -m TEXT or --body -")
648 }
649 stamp := now.Format(knot.CommentStamp)
650 o.form = func(s knotState) (map[string][]byte, string, string, error) {
651 if _, err := guarded(s, id, nil, false); err != nil {
652 return nil, "", "", err
653 }
654 path := fmt.Sprintf("%s/%s/%s-%s.md", knot.CommentsDirectory, id, stamp, o.id)
655 return map[string][]byte{path: knot.RenderComment(&knot.Comment{Author: principal, Body: text})},
656 fmt.Sprintf("knot comment %s", id), id, nil
657 }
658
659 case "claim":
660 id := a.pos[0]
661 if !knot.IsName(a.run) {
662 return o, failure("knot claim takes --run RUN, the ID of the run working on the knot: letters, digits, '.', '_' and '-'")
663 }
664 o.form = func(s knotState) (map[string][]byte, string, string, error) {
665 k, err := guarded(s, id, nil, false)
666 if err != nil {
667 return nil, "", "", err
668 }
669 switch {
670 case k.Type != "outcome" && k.Type != "bug":
671 return nil, "", "", failure(fmt.Sprintf("a%s %s is not claimed; outcomes and bugs are", article(k.Type), k.Type))
672 case k.ClaimedBy == a.run:
673 return nil, "", "", unchanged(fmt.Sprintf("%s is claimed by %s already", id, a.run))
674 case k.ClaimedBy != "":
675 return nil, "", "", conflict(fmt.Sprintf("%s is claimed by %s since %s; unclaim it first", id, k.ClaimedBy, k.ClaimedAt))
676 case !k.Active():
677 return nil, "", "", failure(fmt.Sprintf("%s is %s, and only an active knot is claimed", id, k.Status))
678 }
679 k.ClaimedBy, k.ClaimedAt = a.run, now.Format(time.RFC3339)
680 if k.Type == "outcome" && k.Status == "open" {
681 k.Status = "in-progress"
682 }
683 return put(k), fmt.Sprintf("knot claim %s: %s", id, a.run), id, nil
684 }
685
686 case "unclaim":
687 id := a.pos[0]
688 o.form = func(s knotState) (map[string][]byte, string, string, error) {
689 // The claim released is the one first read. A retry that finds
690 // another claim, or none, reports a conflict: the claim changed
691 // meanwhile, and what the knot holds now is not this
692 // operation's to release.
693 k, err := guarded(s, id, []string{"claimed_by", "claimed_at"}, false)
694 if err != nil {
695 return nil, "", "", err
696 }
697 if k.ClaimedBy != first["claimed_by"] || k.ClaimedAt != first["claimed_at"] {
698 return nil, "", "", conflict(fmt.Sprintf("%s's claim changed from %s to %s while this was written; read it again", id, claimOf(first["claimed_by"], first["claimed_at"]), claimOf(k.ClaimedBy, k.ClaimedAt)))
699 }
700 if k.ClaimedBy == "" {
701 return nil, "", "", unchanged(fmt.Sprintf("%s is not claimed", id))
702 }
703 run := k.ClaimedBy
704 k.ClaimedBy, k.ClaimedAt = "", ""
705 return put(k), fmt.Sprintf("knot unclaim %s: %s", id, run), id, nil
706 }
707 }
708 return o, nil
709}
710
711// assignment is one <field>=<value>.
712type assignment struct{ field, value string }
713
714func parseAssignments(list []string, what string) ([]assignment, error) {
715 var out []assignment
716 for _, s := range list {
717 field, value, ok := strings.Cut(s, "=")
718 if !ok || field == "" {
719 return nil, failure(fmt.Sprintf("%s takes <field>=<value>, and %q is not one", what, s))
720 }
721 out = append(out, assignment{field, value})
722 }
723 return out, nil
724}
725
726// claimOf says who holds a claim and since when, or that there is none.
727func claimOf(by, at string) string {
728 if by == "" {
729 return "none"
730 }
731 return by + " since " + at
732}
733
734func fieldNames() []string {
735 var names []string
736 for _, f := range knot.Fields {
737 names = append(names, f.Name)
738 }
739 return names
740}
741
742func settable() []string {
743 var names []string
744 for _, f := range knot.Fields {
745 if f.Set == "set" {
746 names = append(names, f.Name)
747 }
748 }
749 return names
750}
751
752func setField(k *knot.Knot, field, value string) {
753 switch field {
754 case "status":
755 k.Status = value
756 case "title":
757 k.Title = value
758 case "source":
759 k.Source = value
760 case "owner":
761 k.Owner = value
762 case "target":
763 k.Target = value
764 case "graduated_into":
765 k.GraduatedInto = value
766 }
767}
768
769func sortedSet(list []string) []string {
770 out := slices.Clone(list)
771 if out == nil {
772 out = []string{}
773 }
774 slices.Sort(out)
775 return slices.Compact(out)
776}
777
778func without(list, drop []string) []string {
779 var out []string
780 for _, x := range list {
781 if !slices.Contains(drop, x) {
782 out = append(out, x)
783 }
784 }
785 return out
786}
787
788func article(word string) string {
789 if word != "" && strings.ContainsRune("aeiou", rune(word[0])) {
790 return "n"
791 }
792 return ""
793}
794
795// write forms the operation on origin's tip, validates what it would
796// leave by the rules the hook applies, and pushes it with a lease on that
797// tip, until it lands or knot.Attempts tries have failed.
798//
799// A push that fails may have landed all the same: the connection can drop
800// after origin took it. So after every failure but a refusal by origin's
801// hook, the operation is looked for on the ref before it is formed again,
802// and it is formed again only once a search has found it absent. A search
803// that fails uses up a try.
804func (r remote) write(g git, o op, principal string, asJSON bool, w io.Writer) error {
805 search := false
806 for attempt := 1; attempt <= knot.Attempts; attempt++ {
807 if attempt > 1 {
808 time.Sleep(time.Duration(attempt*(50+mrand.IntN(200))) * time.Millisecond)
809 }
810 if search {
811 found, err := r.find(o.id)
812 if err != nil {
813 continue
814 }
815 if found != "" {
816 return r.reportAt(found, o, asJSON, w)
817 }
818 search = false
819 }
820 s, err := r.read()
821 if err != nil {
822 return err
823 }
824 files, subject, id, err := o.form(s)
825 if err != nil {
826 return err
827 }
828 commit, after, err := r.commit(g, s, files, knot.Message(subject, o.id), principal)
829 if err != nil {
830 return err
831 }
832 refused, err := r.push(commit, s.tip)
833 if err == nil {
834 return r.report(after, id, o.id, commit, subject, asJSON, w)
835 }
836 if refused != "" {
837 return failure("origin refused the write:\n" + refused)
838 }
839 search = true
840 }
841 if found, err := r.find(o.id); err == nil && found != "" {
842 return r.reportAt(found, o, asJSON, w)
843 }
844 return failure(fmt.Sprintf("origin did not take the write after %d tries", knot.Attempts))
845}
846
847// reportAt reports an operation found on the ref at commit, as write
848// reports one it pushed. The commit's subject names the knot:
849// knot <verb> <id>, and what the operation did after a colon.
850func (r remote) reportAt(commit string, o op, asJSON bool, w io.Writer) error {
851 s, err := r.readAt(commit)
852 if err != nil {
853 return err
854 }
855 subject, _ := r.g.output(true, "log", "-1", "--format=%s", commit)
856 id := ""
857 if fields := strings.Fields(subject); len(fields) >= 3 {
858 id = strings.TrimSuffix(fields[2], ":")
859 }
860 return r.report(s, id, o.id, commit, subject, asJSON, w)
861}
862
863// commit builds the operation's commit on a private index: the tip's tree
864// with the files written over it. It holds the result to every rule the
865// hook applies, as the principal pushing it, and returns the commit and
866// the graph it leaves.
867func (r remote) commit(g git, s knotState, files map[string][]byte, message, principal string) (string, knotState, error) {
868 tmp, err := os.MkdirTemp("", "valley-knot-")
869 if err != nil {
870 return "", knotState{}, failure("could not make a private index")
871 }
872 defer os.RemoveAll(tmp)
873 email, err := g.output(true, "config", "user.email")
874 if err != nil || email == "" {
875 email = principal + "@valley.invalid"
876 }
877 c := r.g
878 c.env = append(slices.Clone(c.env), "GIT_INDEX_FILE="+filepath.Join(tmp, "index"),
879 "GIT_AUTHOR_NAME="+principal, "GIT_AUTHOR_EMAIL="+email,
880 "GIT_COMMITTER_NAME="+principal, "GIT_COMMITTER_EMAIL="+email)
881 readTree := []string{"read-tree", "--empty"}
882 if s.tip != "" {
883 readTree = []string{"read-tree", s.tip}
884 }
885 if _, err := c.output(false, readTree...); err != nil {
886 return "", knotState{}, failure("could not read the graph into a private index")
887 }
888 blobs := maps(s.blobs)
889 var info strings.Builder
890 paths := make([]string, 0, len(files))
891 for p := range files {
892 paths = append(paths, p)
893 }
894 sort.Strings(paths)
895 for _, p := range paths {
896 oid, err := c.input(false, bytes.NewReader(files[p]), "hash-object", "-w", "--stdin")
897 if err != nil {
898 return "", knotState{}, failure("could not write " + p)
899 }
900 blobs[oid] = files[p]
901 fmt.Fprintf(&info, "100644 %s\t%s\n", oid, p)
902 }
903 if _, err := c.input(false, strings.NewReader(info.String()), "update-index", "--add", "--index-info"); err != nil {
904 return "", knotState{}, failure("could not stage the write")
905 }
906 tree, err := c.output(false, "write-tree")
907 if err != nil {
908 return "", knotState{}, failure("could not write the graph's tree")
909 }
910 entries, err := r.listing(tree)
911 if err != nil {
912 return "", knotState{}, err
913 }
914 idx, err := knot.Layout(entries)
915 if err == nil {
916 after := knotState{blobs: blobs}
917 err = knot.Push{Old: s.graph.Index, New: idx, Read: after.read, Pusher: principal}.Check()
918 }
919 if err != nil {
920 return "", knotState{}, failure("the write would leave the graph invalid: " + err.Error())
921 }
922 args := []string{"commit-tree", tree}
923 if s.tip != "" {
924 args = append(args, "-p", s.tip)
925 }
926 commit, err := c.input(false, strings.NewReader(message), append(args, "-F", "-")...)
927 if err != nil {
928 return "", knotState{}, failure("could not write the commit")
929 }
930 after := knotState{tip: commit, blobs: blobs}
931 if after.graph, err = knot.Load(idx, after.read); err != nil {
932 return "", knotState{}, failure("the write would leave the graph invalid: " + err.Error())
933 }
934 return commit, after, nil
935}
936
937func maps(m map[string][]byte) map[string][]byte {
938 out := make(map[string][]byte, len(m))
939 for k, v := range m {
940 out[k] = v
941 }
942 return out
943}
944
945// push moves the ref on origin from old to commit, leased on old: it is
946// refused if the ref has moved since it was read, and a ref that did not
947// exist must still not exist. refused is what origin's hook said when it
948// refused the push. It is "" for a failure that may have been anything:
949// a lease that failed, a connection that dropped, or a push that passed
950// the hook and then lost the ref's lock to another push landing at once,
951// which git reports as remote rejected too.
952func (r remote) push(commit, old string) (refused string, err error) {
953 cmd := exec.Command("git", "push", "--porcelain", "--quiet", "--force-with-lease="+knot.Ref+":"+old,
954 "origin", commit+":"+knot.Ref)
955 cmd.Env, cmd.Dir = r.g.env, r.g.dir
956 var stdout, stderr bytes.Buffer
957 cmd.Stdout, cmd.Stderr = &stdout, &stderr
958 if err := cmd.Run(); err == nil {
959 return "", nil
960 } else if strings.Contains(stdout.String(), "hook declined") {
961 var lines []string
962 for _, line := range strings.Split(stderr.String(), "\n") {
963 if said, ok := strings.CutPrefix(line, "remote: "); ok {
964 lines = append(lines, said)
965 }
966 }
967 if len(lines) == 0 {
968 lines = []string{strings.TrimSpace(stdout.String())}
969 }
970 return strings.Join(lines, "\n"), err
971 } else {
972 return "", err
973 }
974}
975
976// find looks for the operation among the latest knot.OpSearch commits of
977// the ref on origin, and returns the commit that recorded it, or "".
978func (r remote) find(op string) (string, error) {
979 tip, err := remoteRef(r.g, "origin", knot.Ref)
980 if err != nil || tip == "" {
981 return "", err
982 }
983 if err := fetch(r.g, tip); err != nil {
984 return "", err
985 }
986 out, err := r.g.output(true, "log", "--format=%x1e%H%x1f%B", "-n", strconv.Itoa(knot.OpSearch), tip)
987 if err != nil {
988 return "", err
989 }
990 for _, rec := range strings.Split(out, "\x1e") {
991 commit, message, ok := strings.Cut(rec, "\x1f")
992 if !ok {
993 continue
994 }
995 if found, err := knot.OpOf(message); err == nil && found == op {
996 return commit, nil
997 }
998 }
999 return "", nil
1000}
1001
1002// report says what a write did.
1003func (r remote) report(s knotState, id, op, commit, subject string, asJSON bool, w io.Writer) error {
1004 if asJSON {
1005 var j *jsonKnot
1006 if k, ok := s.graph.Knots[id]; ok {
1007 j = r.jsonKnot(s, k, true, nil)
1008 }
1009 doc := struct {
1010 Schema string `json:"schema"`
1011 Project string `json:"project"`
1012 Op string `json:"op"`
1013 Commit string `json:"commit"`
1014 Knot *jsonKnot `json:"knot"`
1015 }{"valley-knot-op/v1", r.name, op, commit, j}
1016 return writeKnotJSON(w, doc)
1017 }
1018 _, err := fmt.Fprintf(w, "%s (%s)\n", visible(subject), short(commit))
1019 return err
1020}
1021
1022// jsonKnot is one knot as --json prints it: its fields, what the graph
1023// derives of it, and, for show, its body and comments.
1024type jsonKnot struct {
1025 ID string `json:"id"`
1026 Type string `json:"type"`
1027 Status string `json:"status"`
1028 Active bool `json:"active"`
1029 Title string `json:"title"`
1030 Created string `json:"created"`
1031 CreatedBy string `json:"created_by"`
1032 Source string `json:"source,omitempty"`
1033 Parent string `json:"parent,omitempty"`
1034 Owner string `json:"owner,omitempty"`
1035 BlockedBy []string `json:"blocked_by"`
1036 ClaimedBy string `json:"claimed_by,omitempty"`
1037 ClaimedAt string `json:"claimed_at,omitempty"`
1038 Changes []string `json:"changes"`
1039 Target string `json:"target,omitempty"`
1040 GraduatedInto string `json:"graduated_into,omitempty"`
1041 Path string `json:"path"`
1042 Body *string `json:"body,omitempty"`
1043 Comments []jsonComment `json:"comments,omitempty"`
1044 CommentCount int `json:"comment_count"`
1045 knot.View
1046}
1047
1048type jsonComment struct {
1049 Author string `json:"author"`
1050 At string `json:"at"`
1051 Op string `json:"op"`
1052 Body string `json:"body"`
1053}
1054
1055func (r remote) jsonKnot(s knotState, k *knot.Knot, full bool, foreign knot.Foreign) *jsonKnot {
1056 j := &jsonKnot{ID: k.ID, Type: k.Type, Status: k.Status, Active: k.Active(), Title: k.Title,
1057 Created: k.Created, CreatedBy: k.CreatedBy, Source: k.Source, Parent: k.Parent, Owner: k.Owner,
1058 BlockedBy: nonNil(k.BlockedBy), ClaimedBy: k.ClaimedBy, ClaimedAt: k.ClaimedAt,
1059 Changes: nonNil(k.Changes), Target: k.Target, GraduatedInto: k.GraduatedInto, Path: k.Path(),
1060 CommentCount: len(s.graph.Comments[k.ID]), View: s.graph.View(k.ID, clock(), foreign)}
1061 if full {
1062 body := k.Body
1063 j.Body = &body
1064 j.Comments = []jsonComment{}
1065 for _, c := range s.graph.Comments[k.ID] {
1066 j.Comments = append(j.Comments, jsonComment{Author: c.Author, At: c.At.Format(time.RFC3339), Op: c.Op, Body: c.Body})
1067 }
1068 }
1069 return j
1070}
1071
1072func nonNil(list []string) []string {
1073 if list == nil {
1074 return []string{}
1075 }
1076 return list
1077}
1078
1079// foreign resolves references to other projects' knots, reading each
1080// project's graph once.
1081func (r remote) foreign(g git) knot.Foreign {
1082 read := map[string]*knot.Graph{}
1083 failed := map[string]error{}
1084 return func(ref string) (*knot.Knot, bool, error) {
1085 project, id, _ := strings.Cut(ref, ":")
1086 if err := failed[project]; err != nil {
1087 return nil, false, err
1088 }
1089 graph := read[project]
1090 if graph == nil {
1091 other, err := knotRemote(g, project)
1092 var s knotState
1093 if err == nil {
1094 s, err = other.read()
1095 }
1096 if err != nil {
1097 failed[project] = err
1098 return nil, false, err
1099 }
1100 graph = s.graph
1101 read[project] = graph
1102 }
1103 k, ok := graph.Knots[id]
1104 return k, ok, nil
1105 }
1106}
1107
1108func knotShow(r remote, a knotArgs, w io.Writer) error {
1109 s, err := r.read()
1110 if err != nil {
1111 return err
1112 }
1113 id := a.pos[0]
1114 k, ok := s.graph.Knots[id]
1115 if !ok {
1116 return failure(fmt.Sprintf("the graph of %s holds no knot %s", r.name, id))
1117 }
1118 j := r.jsonKnot(s, k, true, r.foreign(r.g))
1119 if a.json {
1120 return writeKnotJSON(w, struct {
1121 Schema string `json:"schema"`
1122 Project string `json:"project"`
1123 Tip string `json:"tip"`
1124 Knot *jsonKnot `json:"knot"`
1125 }{"valley-knot/v1", r.name, s.tip, j})
1126 }
1127 var b strings.Builder
1128 title := func(id string) string {
1129 if o, ok := s.graph.Knots[id]; ok {
1130 return fmt.Sprintf("%s (%s) %s", id, o.Status, visible(o.Title))
1131 }
1132 return id
1133 }
1134 fmt.Fprintf(&b, "%s %s %s\n%s\n", k.ID, k.Type, k.Status, visible(k.Title))
1135 fmt.Fprintf(&b, "created %s by %s\n", k.Created, visible(k.CreatedBy))
1136 line := func(label, value string) {
1137 if value != "" {
1138 fmt.Fprintf(&b, "%-11s %s\n", label+":", value)
1139 }
1140 }
1141 line("source", visible(k.Source))
1142 if k.Parent != "" {
1143 line("parent", title(k.Parent))
1144 }
1145 line("owner", visible(k.Owner))
1146 line("target", visible(k.Target))
1147 if j.Claim != nil {
1148 stale := ""
1149 if j.Claim.Stale {
1150 stale = ", stale"
1151 }
1152 line("claimed", fmt.Sprintf("by %s %s ago%s", visible(j.Claim.By), age(j.Claim.AgeSeconds), stale))
1153 }
1154 for _, ref := range k.BlockedBy {
1155 mark := ""
1156 switch {
1157 case slices.Contains(j.Dangling, ref):
1158 mark = " (dangling: its project holds no such knot)"
1159 case slices.Contains(j.Unresolved, ref):
1160 mark = " (unresolved: its project could not be read)"
1161 case slices.Contains(j.ClearedByEnding, ref):
1162 mark = " (cleared by ending)"
1163 }
1164 line("blocked by", title(ref)+mark)
1165 }
1166 for _, other := range j.Blocks {
1167 line("blocks", title(other))
1168 }
1169 for _, other := range j.Children {
1170 line("child", title(other))
1171 }
1172 if j.Progress != nil {
1173 line("progress", fmt.Sprintf("%d of %d", j.Progress.Done, j.Progress.Of))
1174 }
1175 for _, c := range k.Changes {
1176 line("change", visible(c))
1177 }
1178 line("graduated", k.GraduatedInto)
1179 if j.Ready {
1180 b.WriteString("ready\n")
1181 }
1182 if k.Body != "" {
1183 b.WriteString("\n" + visible(k.Body))
1184 }
1185 for _, c := range s.graph.Comments[k.ID] {
1186 fmt.Fprintf(&b, "\n— %s, %s\n%s", visible(c.Author), c.At.Format("2006-01-02 15:04Z"), visible(c.Body))
1187 }
1188 _, err = io.WriteString(w, b.String())
1189 return err
1190}
1191
1192func knotList(r remote, a knotArgs, w io.Writer) error {
1193 if a.typ != "" {
1194 if _, ok := knot.TypeNamed(a.typ); !ok {
1195 return failure(fmt.Sprintf("%q is no type of knot; the types are %s", a.typ, strings.Join(knot.TypeNames(), ", ")))
1196 }
1197 }
1198 if a.status != "" && a.status != "active" && a.status != "terminal" && !anyStatus(a.status) {
1199 return failure(fmt.Sprintf("%q is no status; --status takes active, terminal, or one of %s", a.status, strings.Join(allStatuses(), ", ")))
1200 }
1201 s, err := r.read()
1202 if err != nil {
1203 return err
1204 }
1205 foreign := r.foreign(r.g)
1206 var list []*jsonKnot
1207 for _, id := range s.graph.IDs() {
1208 k := s.graph.Knots[id]
1209 switch {
1210 case a.typ != "" && k.Type != a.typ,
1211 a.owner != "" && k.Owner != a.owner,
1212 a.status == "active" && !k.Active(),
1213 a.status == "terminal" && k.Active(),
1214 a.status != "" && a.status != "active" && a.status != "terminal" && k.Status != a.status:
1215 continue
1216 }
1217 j := r.jsonKnot(s, k, false, foreign)
1218 if a.ready && !j.Ready {
1219 continue
1220 }
1221 list = append(list, j)
1222 }
1223 if a.json {
1224 if list == nil {
1225 list = []*jsonKnot{}
1226 }
1227 return writeKnotJSON(w, struct {
1228 Schema string `json:"schema"`
1229 Project string `json:"project"`
1230 Tip string `json:"tip"`
1231 Knots []*jsonKnot `json:"knots"`
1232 }{"valley-knots/v1", r.name, s.tip, list})
1233 }
1234 var b strings.Builder
1235 for _, j := range list {
1236 var notes []string
1237 if j.Claim != nil {
1238 notes = append(notes, "claimed by "+visible(j.Claim.By))
1239 }
1240 if len(j.WaitingOn) > 0 {
1241 notes = append(notes, "waits on "+strings.Join(j.WaitingOn, ", "))
1242 }
1243 if j.Ready {
1244 notes = append(notes, "ready")
1245 }
1246 note := ""
1247 if len(notes) > 0 {
1248 note = " [" + strings.Join(notes, "; ") + "]"
1249 }
1250 fmt.Fprintf(&b, "%-11s %-8s %-11s %s%s\n", j.ID, j.Type, j.Status, visible(j.Title), note)
1251 }
1252 _, err = io.WriteString(w, b.String())
1253 return err
1254}
1255
1256func anyStatus(s string) bool { return slices.Contains(allStatuses(), s) }
1257
1258func allStatuses() []string {
1259 var all []string
1260 for _, t := range knot.Types {
1261 for _, s := range t.Statuses() {
1262 if !slices.Contains(all, s) {
1263 all = append(all, s)
1264 }
1265 }
1266 }
1267 return all
1268}
1269
1270func age(seconds int64) string {
1271 d := time.Duration(seconds) * time.Second
1272 switch {
1273 case d < time.Hour:
1274 return fmt.Sprintf("%dm", int(d.Minutes()))
1275 case d < 48*time.Hour:
1276 return fmt.Sprintf("%dh", int(d.Hours()))
1277 }
1278 return fmt.Sprintf("%dd", int(d.Hours()/24))
1279}
1280
1281// visible is text made safe to print to a terminal: every control
1282// character but newline and tab, and every character that reorders the
1283// text around it, is written as an escape instead. The graph refuses
1284// control characters, so this is a second guard rather than the first.
1285func visible(s string) string {
1286 var b strings.Builder
1287 for _, r := range s {
1288 if r != '\n' && r != '\t' && (unicode.IsControl(r) || unicode.Is(unicode.Bidi_Control, r)) {
1289 fmt.Fprintf(&b, "\\u{%04x}", r)
1290 continue
1291 }
1292 b.WriteRune(r)
1293 }
1294 return b.String()
1295}
1296
1297// writeKnotJSON prints one indented JSON document.
1298func writeKnotJSON(w io.Writer, v any) error {
1299 enc := json.NewEncoder(w)
1300 enc.SetEscapeHTML(false)
1301 enc.SetIndent("", " ")
1302 return enc.Encode(v)
1303}