gunk-dev/the-valley

knot.go

source7b33cff6a453main's published tip history
39.9 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 // Finishing a knot releases its claim in the same commit.
552 if !k.Active() {
553 k.ClaimedBy, k.ClaimedAt = "", ""
554 }
555 if string(knot.Render(k)) == before {
556 return nil, "", "", unchanged(fmt.Sprintf("%s already holds that; nothing to change", id))
557 }
558 return put(k), fmt.Sprintf("knot set %s: %s", id, strings.Join(a.pos[1:], " ")), id, nil
559 }
560
561 case "link", "unlink":
562 id := a.pos[0]
563 if len(a.blockedBy) == 0 && !a.hasParent && len(a.changes) == 0 {
564 return o, failure(fmt.Sprintf("knot %s takes --blocked-by, --parent or --change", a.verb))
565 }
566 o.form = func(s knotState) (map[string][]byte, string, string, error) {
567 var fields []string
568 if a.hasParent {
569 fields = []string{"parent"}
570 }
571 k, err := guarded(s, id, fields, true)
572 if err != nil {
573 return nil, "", "", err
574 }
575 before := string(knot.Render(k))
576 var did []string
577 if a.verb == "link" {
578 if a.hasParent {
579 if k.Parent != "" && k.Parent != a.parent {
580 return nil, "", "", conflict(fmt.Sprintf("%s's parent is %s; unlink it first to give it another", id, k.Parent))
581 }
582 k.Parent = a.parent
583 did = append(did, "parent "+a.parent)
584 }
585 if len(a.blockedBy) > 0 {
586 k.BlockedBy = sortedSet(append(slices.Clone(k.BlockedBy), a.blockedBy...))
587 did = append(did, "blocked by "+strings.Join(a.blockedBy, ", "))
588 }
589 if len(a.changes) > 0 {
590 k.Changes = sortedSet(append(slices.Clone(k.Changes), a.changes...))
591 did = append(did, "change "+strings.Join(a.changes, ", "))
592 }
593 } else {
594 if a.hasParent {
595 if k.Parent != a.parent {
596 return nil, "", "", conflict(fmt.Sprintf("%s's parent is %q, not %s", id, k.Parent, a.parent))
597 }
598 k.Parent = ""
599 did = append(did, "parent "+a.parent)
600 }
601 if len(a.blockedBy) > 0 {
602 k.BlockedBy = without(k.BlockedBy, a.blockedBy)
603 if k.BlockedBy == nil && (k.Type == "outcome" || k.Type == "bug") {
604 k.BlockedBy = []string{}
605 }
606 did = append(did, "blocked by "+strings.Join(a.blockedBy, ", "))
607 }
608 if len(a.changes) > 0 {
609 k.Changes = without(k.Changes, a.changes)
610 did = append(did, "change "+strings.Join(a.changes, ", "))
611 }
612 }
613 if string(knot.Render(k)) == before {
614 return nil, "", "", unchanged(fmt.Sprintf("%s already holds that; nothing to change", id))
615 }
616 return put(k), fmt.Sprintf("knot %s %s: %s", a.verb, id, strings.Join(did, "; ")), id, nil
617 }
618
619 case "edit":
620 id := a.pos[0]
621 if !a.stdin {
622 return o, failure("knot edit takes --body -, and reads the new body from stdin")
623 }
624 o.form = func(s knotState) (map[string][]byte, string, string, error) {
625 k, err := guarded(s, id, nil, true)
626 if err != nil {
627 return nil, "", "", err
628 }
629 if first["body"] == "" {
630 first["body"] = "read:" + k.Body
631 } else if first["body"] != "read:"+k.Body {
632 return nil, "", "", conflict(fmt.Sprintf("%s's body changed while this was written; read it again", id))
633 }
634 if k.Body == body {
635 return nil, "", "", unchanged(fmt.Sprintf("%s's body is that already; nothing to change", id))
636 }
637 k.Body = body
638 return put(k), fmt.Sprintf("knot edit %s", id), id, nil
639 }
640
641 case "comment":
642 id := a.pos[0]
643 text := body
644 if a.hasMessage {
645 if a.stdin {
646 return o, failure("knot comment takes -m or --body -, not both")
647 }
648 text = knot.NormalBody(a.message)
649 }
650 if text == "" {
651 return o, failure("knot comment takes the comment, with -m TEXT or --body -")
652 }
653 stamp := now.Format(knot.CommentStamp)
654 o.form = func(s knotState) (map[string][]byte, string, string, error) {
655 if _, err := guarded(s, id, nil, false); err != nil {
656 return nil, "", "", err
657 }
658 path := fmt.Sprintf("%s/%s/%s-%s.md", knot.CommentsDirectory, id, stamp, o.id)
659 return map[string][]byte{path: knot.RenderComment(&knot.Comment{Author: principal, Body: text})},
660 fmt.Sprintf("knot comment %s", id), id, nil
661 }
662
663 case "claim":
664 id := a.pos[0]
665 if !knot.IsName(a.run) {
666 return o, failure("knot claim takes --run RUN, the ID of the run working on the knot: letters, digits, '.', '_' and '-'")
667 }
668 o.form = func(s knotState) (map[string][]byte, string, string, error) {
669 k, err := guarded(s, id, nil, false)
670 if err != nil {
671 return nil, "", "", err
672 }
673 switch {
674 case k.Type != "outcome" && k.Type != "bug":
675 return nil, "", "", failure(fmt.Sprintf("a%s %s is not claimed; outcomes and bugs are", article(k.Type), k.Type))
676 case k.ClaimedBy == a.run:
677 return nil, "", "", unchanged(fmt.Sprintf("%s is claimed by %s already", id, a.run))
678 case k.ClaimedBy != "":
679 return nil, "", "", conflict(fmt.Sprintf("%s is claimed by %s since %s; unclaim it first", id, k.ClaimedBy, k.ClaimedAt))
680 case !k.Active():
681 return nil, "", "", failure(fmt.Sprintf("%s is %s, and only an active knot is claimed", id, k.Status))
682 }
683 k.ClaimedBy, k.ClaimedAt = a.run, now.Format(time.RFC3339)
684 if k.Type == "outcome" && k.Status == "open" {
685 k.Status = "in-progress"
686 }
687 return put(k), fmt.Sprintf("knot claim %s: %s", id, a.run), id, nil
688 }
689
690 case "unclaim":
691 id := a.pos[0]
692 o.form = func(s knotState) (map[string][]byte, string, string, error) {
693 // The claim released is the one first read. A retry that finds
694 // another claim, or none, reports a conflict: the claim changed
695 // meanwhile, and what the knot holds now is not this
696 // operation's to release.
697 k, err := guarded(s, id, []string{"claimed_by", "claimed_at"}, false)
698 if err != nil {
699 return nil, "", "", err
700 }
701 if k.ClaimedBy != first["claimed_by"] || k.ClaimedAt != first["claimed_at"] {
702 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)))
703 }
704 if k.ClaimedBy == "" {
705 return nil, "", "", unchanged(fmt.Sprintf("%s is not claimed", id))
706 }
707 run := k.ClaimedBy
708 k.ClaimedBy, k.ClaimedAt = "", ""
709 return put(k), fmt.Sprintf("knot unclaim %s: %s", id, run), id, nil
710 }
711 }
712 return o, nil
713}
714
715// assignment is one <field>=<value>.
716type assignment struct{ field, value string }
717
718func parseAssignments(list []string, what string) ([]assignment, error) {
719 var out []assignment
720 for _, s := range list {
721 field, value, ok := strings.Cut(s, "=")
722 if !ok || field == "" {
723 return nil, failure(fmt.Sprintf("%s takes <field>=<value>, and %q is not one", what, s))
724 }
725 out = append(out, assignment{field, value})
726 }
727 return out, nil
728}
729
730// claimOf says who holds a claim and since when, or that there is none.
731func claimOf(by, at string) string {
732 if by == "" {
733 return "none"
734 }
735 return by + " since " + at
736}
737
738func fieldNames() []string {
739 var names []string
740 for _, f := range knot.Fields {
741 names = append(names, f.Name)
742 }
743 return names
744}
745
746func settable() []string {
747 var names []string
748 for _, f := range knot.Fields {
749 if f.Set == "set" {
750 names = append(names, f.Name)
751 }
752 }
753 return names
754}
755
756func setField(k *knot.Knot, field, value string) {
757 switch field {
758 case "status":
759 k.Status = value
760 case "title":
761 k.Title = value
762 case "source":
763 k.Source = value
764 case "owner":
765 k.Owner = value
766 case "target":
767 k.Target = value
768 case "graduated_into":
769 k.GraduatedInto = value
770 }
771}
772
773func sortedSet(list []string) []string {
774 out := slices.Clone(list)
775 if out == nil {
776 out = []string{}
777 }
778 slices.Sort(out)
779 return slices.Compact(out)
780}
781
782func without(list, drop []string) []string {
783 var out []string
784 for _, x := range list {
785 if !slices.Contains(drop, x) {
786 out = append(out, x)
787 }
788 }
789 return out
790}
791
792func article(word string) string {
793 if word != "" && strings.ContainsRune("aeiou", rune(word[0])) {
794 return "n"
795 }
796 return ""
797}
798
799// write forms the operation on origin's tip, validates what it would
800// leave by the rules the hook applies, and pushes it with a lease on that
801// tip, until it lands or knot.Attempts tries have failed.
802//
803// A push that fails may have landed all the same: the connection can drop
804// after origin took it. So after every failure but a refusal by origin's
805// hook, the operation is looked for on the ref before it is formed again,
806// and it is formed again only once a search has found it absent. A search
807// that fails uses up a try.
808func (r remote) write(g git, o op, principal string, asJSON bool, w io.Writer) error {
809 search := false
810 for attempt := 1; attempt <= knot.Attempts; attempt++ {
811 if attempt > 1 {
812 time.Sleep(time.Duration(attempt*(50+mrand.IntN(200))) * time.Millisecond)
813 }
814 if search {
815 found, err := r.find(o.id)
816 if err != nil {
817 continue
818 }
819 if found != "" {
820 return r.reportAt(found, o, asJSON, w)
821 }
822 search = false
823 }
824 s, err := r.read()
825 if err != nil {
826 return err
827 }
828 files, subject, id, err := o.form(s)
829 if err != nil {
830 return err
831 }
832 commit, after, err := r.commit(g, s, files, knot.Message(subject, o.id), principal)
833 if err != nil {
834 return err
835 }
836 refused, err := r.push(commit, s.tip)
837 if err == nil {
838 return r.report(after, id, o.id, commit, subject, asJSON, w)
839 }
840 if refused != "" {
841 return failure("origin refused the write:\n" + refused)
842 }
843 search = true
844 }
845 if found, err := r.find(o.id); err == nil && found != "" {
846 return r.reportAt(found, o, asJSON, w)
847 }
848 return failure(fmt.Sprintf("origin did not take the write after %d tries", knot.Attempts))
849}
850
851// reportAt reports an operation found on the ref at commit, as write
852// reports one it pushed. The commit's subject names the knot:
853// knot <verb> <id>, and what the operation did after a colon.
854func (r remote) reportAt(commit string, o op, asJSON bool, w io.Writer) error {
855 s, err := r.readAt(commit)
856 if err != nil {
857 return err
858 }
859 subject, _ := r.g.output(true, "log", "-1", "--format=%s", commit)
860 id := ""
861 if fields := strings.Fields(subject); len(fields) >= 3 {
862 id = strings.TrimSuffix(fields[2], ":")
863 }
864 return r.report(s, id, o.id, commit, subject, asJSON, w)
865}
866
867// commit builds the operation's commit on a private index: the tip's tree
868// with the files written over it. It holds the result to every rule the
869// hook applies, as the principal pushing it, and returns the commit and
870// the graph it leaves.
871func (r remote) commit(g git, s knotState, files map[string][]byte, message, principal string) (string, knotState, error) {
872 tmp, err := os.MkdirTemp("", "valley-knot-")
873 if err != nil {
874 return "", knotState{}, failure("could not make a private index")
875 }
876 defer os.RemoveAll(tmp)
877 email, err := g.output(true, "config", "user.email")
878 if err != nil || email == "" {
879 email = principal + "@valley.invalid"
880 }
881 c := r.g
882 c.env = append(slices.Clone(c.env), "GIT_INDEX_FILE="+filepath.Join(tmp, "index"),
883 "GIT_AUTHOR_NAME="+principal, "GIT_AUTHOR_EMAIL="+email,
884 "GIT_COMMITTER_NAME="+principal, "GIT_COMMITTER_EMAIL="+email)
885 readTree := []string{"read-tree", "--empty"}
886 if s.tip != "" {
887 readTree = []string{"read-tree", s.tip}
888 }
889 if _, err := c.output(false, readTree...); err != nil {
890 return "", knotState{}, failure("could not read the graph into a private index")
891 }
892 blobs := maps(s.blobs)
893 var info strings.Builder
894 paths := make([]string, 0, len(files))
895 for p := range files {
896 paths = append(paths, p)
897 }
898 sort.Strings(paths)
899 for _, p := range paths {
900 oid, err := c.input(false, bytes.NewReader(files[p]), "hash-object", "-w", "--stdin")
901 if err != nil {
902 return "", knotState{}, failure("could not write " + p)
903 }
904 blobs[oid] = files[p]
905 fmt.Fprintf(&info, "100644 %s\t%s\n", oid, p)
906 }
907 if _, err := c.input(false, strings.NewReader(info.String()), "update-index", "--add", "--index-info"); err != nil {
908 return "", knotState{}, failure("could not stage the write")
909 }
910 tree, err := c.output(false, "write-tree")
911 if err != nil {
912 return "", knotState{}, failure("could not write the graph's tree")
913 }
914 entries, err := r.listing(tree)
915 if err != nil {
916 return "", knotState{}, err
917 }
918 idx, err := knot.Layout(entries)
919 if err == nil {
920 after := knotState{blobs: blobs}
921 err = knot.Push{Old: s.graph.Index, New: idx, Read: after.read, Pusher: principal}.Check()
922 }
923 if err != nil {
924 return "", knotState{}, failure("the write would leave the graph invalid: " + err.Error())
925 }
926 args := []string{"commit-tree", tree}
927 if s.tip != "" {
928 args = append(args, "-p", s.tip)
929 }
930 commit, err := c.input(false, strings.NewReader(message), append(args, "-F", "-")...)
931 if err != nil {
932 return "", knotState{}, failure("could not write the commit")
933 }
934 after := knotState{tip: commit, blobs: blobs}
935 if after.graph, err = knot.Load(idx, after.read); err != nil {
936 return "", knotState{}, failure("the write would leave the graph invalid: " + err.Error())
937 }
938 return commit, after, nil
939}
940
941func maps(m map[string][]byte) map[string][]byte {
942 out := make(map[string][]byte, len(m))
943 for k, v := range m {
944 out[k] = v
945 }
946 return out
947}
948
949// push moves the ref on origin from old to commit, leased on old: it is
950// refused if the ref has moved since it was read, and a ref that did not
951// exist must still not exist. refused is what origin's hook said when it
952// refused the push. It is "" for a failure that may have been anything:
953// a lease that failed, a connection that dropped, or a push that passed
954// the hook and then lost the ref's lock to another push landing at once,
955// which git reports as remote rejected too.
956func (r remote) push(commit, old string) (refused string, err error) {
957 cmd := exec.Command("git", "push", "--porcelain", "--quiet", "--force-with-lease="+knot.Ref+":"+old,
958 "origin", commit+":"+knot.Ref)
959 cmd.Env, cmd.Dir = r.g.env, r.g.dir
960 var stdout, stderr bytes.Buffer
961 cmd.Stdout, cmd.Stderr = &stdout, &stderr
962 if err := cmd.Run(); err == nil {
963 return "", nil
964 } else if strings.Contains(stdout.String(), "hook declined") {
965 var lines []string
966 for _, line := range strings.Split(stderr.String(), "\n") {
967 if said, ok := strings.CutPrefix(line, "remote: "); ok {
968 lines = append(lines, said)
969 }
970 }
971 if len(lines) == 0 {
972 lines = []string{strings.TrimSpace(stdout.String())}
973 }
974 return strings.Join(lines, "\n"), err
975 } else {
976 return "", err
977 }
978}
979
980// find looks for the operation among the latest knot.OpSearch commits of
981// the ref on origin, and returns the commit that recorded it, or "".
982func (r remote) find(op string) (string, error) {
983 tip, err := remoteRef(r.g, "origin", knot.Ref)
984 if err != nil || tip == "" {
985 return "", err
986 }
987 if err := fetch(r.g, tip); err != nil {
988 return "", err
989 }
990 out, err := r.g.output(true, "log", "--format=%x1e%H%x1f%B", "-n", strconv.Itoa(knot.OpSearch), tip)
991 if err != nil {
992 return "", err
993 }
994 for _, rec := range strings.Split(out, "\x1e") {
995 commit, message, ok := strings.Cut(rec, "\x1f")
996 if !ok {
997 continue
998 }
999 if found, err := knot.OpOf(message); err == nil && found == op {
1000 return commit, nil
1001 }
1002 }
1003 return "", nil
1004}
1005
1006// report says what a write did.
1007func (r remote) report(s knotState, id, op, commit, subject string, asJSON bool, w io.Writer) error {
1008 if asJSON {
1009 var j *jsonKnot
1010 if k, ok := s.graph.Knots[id]; ok {
1011 j = r.jsonKnot(s, k, true, nil)
1012 }
1013 doc := struct {
1014 Schema string `json:"schema"`
1015 Project string `json:"project"`
1016 Op string `json:"op"`
1017 Commit string `json:"commit"`
1018 Knot *jsonKnot `json:"knot"`
1019 }{"valley-knot-op/v1", r.name, op, commit, j}
1020 return writeKnotJSON(w, doc)
1021 }
1022 _, err := fmt.Fprintf(w, "%s (%s)\n", visible(subject), short(commit))
1023 return err
1024}
1025
1026// jsonKnot is one knot as --json prints it: its fields, what the graph
1027// derives of it, and, for show, its body and comments.
1028type jsonKnot struct {
1029 ID string `json:"id"`
1030 Type string `json:"type"`
1031 Status string `json:"status"`
1032 Active bool `json:"active"`
1033 Title string `json:"title"`
1034 Created string `json:"created"`
1035 CreatedBy string `json:"created_by"`
1036 Source string `json:"source,omitempty"`
1037 Parent string `json:"parent,omitempty"`
1038 Owner string `json:"owner,omitempty"`
1039 BlockedBy []string `json:"blocked_by"`
1040 ClaimedBy string `json:"claimed_by,omitempty"`
1041 ClaimedAt string `json:"claimed_at,omitempty"`
1042 Changes []string `json:"changes"`
1043 Target string `json:"target,omitempty"`
1044 GraduatedInto string `json:"graduated_into,omitempty"`
1045 Path string `json:"path"`
1046 Body *string `json:"body,omitempty"`
1047 Comments []jsonComment `json:"comments,omitempty"`
1048 CommentCount int `json:"comment_count"`
1049 knot.View
1050}
1051
1052type jsonComment struct {
1053 Author string `json:"author"`
1054 At string `json:"at"`
1055 Op string `json:"op"`
1056 Body string `json:"body"`
1057}
1058
1059func (r remote) jsonKnot(s knotState, k *knot.Knot, full bool, foreign knot.Foreign) *jsonKnot {
1060 j := &jsonKnot{ID: k.ID, Type: k.Type, Status: k.Status, Active: k.Active(), Title: k.Title,
1061 Created: k.Created, CreatedBy: k.CreatedBy, Source: k.Source, Parent: k.Parent, Owner: k.Owner,
1062 BlockedBy: nonNil(k.BlockedBy), ClaimedBy: k.ClaimedBy, ClaimedAt: k.ClaimedAt,
1063 Changes: nonNil(k.Changes), Target: k.Target, GraduatedInto: k.GraduatedInto, Path: k.Path(),
1064 CommentCount: len(s.graph.Comments[k.ID]), View: s.graph.View(k.ID, clock(), foreign)}
1065 if full {
1066 body := k.Body
1067 j.Body = &body
1068 j.Comments = []jsonComment{}
1069 for _, c := range s.graph.Comments[k.ID] {
1070 j.Comments = append(j.Comments, jsonComment{Author: c.Author, At: c.At.Format(time.RFC3339), Op: c.Op, Body: c.Body})
1071 }
1072 }
1073 return j
1074}
1075
1076func nonNil(list []string) []string {
1077 if list == nil {
1078 return []string{}
1079 }
1080 return list
1081}
1082
1083// foreign resolves references to other projects' knots, reading each
1084// project's graph once.
1085func (r remote) foreign(g git) knot.Foreign {
1086 // Another project's git speaks only through its error, which the
1087 // reference reports as dangling; its stderr stays quiet.
1088 g.stderr = io.Discard
1089 f := &foreignGraphs{g: g, graphs: map[string]*knot.Graph{}, failed: map[string]error{}}
1090 return f.resolve
1091}
1092
1093func knotShow(r remote, a knotArgs, w io.Writer) error {
1094 s, err := r.read()
1095 if err != nil {
1096 return err
1097 }
1098 id := a.pos[0]
1099 k, ok := s.graph.Knots[id]
1100 if !ok {
1101 return failure(fmt.Sprintf("the graph of %s holds no knot %s", r.name, id))
1102 }
1103 j := r.jsonKnot(s, k, true, r.foreign(r.g))
1104 if a.json {
1105 return writeKnotJSON(w, struct {
1106 Schema string `json:"schema"`
1107 Project string `json:"project"`
1108 Tip string `json:"tip"`
1109 Knot *jsonKnot `json:"knot"`
1110 }{"valley-knot/v1", r.name, s.tip, j})
1111 }
1112 var b strings.Builder
1113 title := func(id string) string {
1114 if o, ok := s.graph.Knots[id]; ok {
1115 return fmt.Sprintf("%s (%s) %s", id, o.Status, visible(o.Title))
1116 }
1117 return id
1118 }
1119 fmt.Fprintf(&b, "%s %s %s\n%s\n", k.ID, k.Type, k.Status, visible(k.Title))
1120 fmt.Fprintf(&b, "created %s by %s\n", k.Created, visible(k.CreatedBy))
1121 line := func(label, value string) {
1122 if value != "" {
1123 fmt.Fprintf(&b, "%-11s %s\n", label+":", value)
1124 }
1125 }
1126 line("source", visible(k.Source))
1127 if k.Parent != "" {
1128 line("parent", title(k.Parent))
1129 }
1130 line("owner", visible(k.Owner))
1131 line("target", visible(k.Target))
1132 if j.Claim != nil {
1133 stale := ""
1134 if j.Claim.Stale {
1135 stale = ", stale"
1136 }
1137 line("claimed", fmt.Sprintf("by %s %s ago%s", visible(j.Claim.By), age(j.Claim.AgeSeconds), stale))
1138 }
1139 for _, ref := range k.BlockedBy {
1140 mark := ""
1141 switch {
1142 case slices.Contains(j.Dangling, ref):
1143 mark = " (dangling: its project holds no such knot)"
1144 case slices.Contains(j.Unresolved, ref):
1145 mark = " (dangling: its project could not be read)"
1146 case slices.Contains(j.ClearedByEnding, ref):
1147 mark = " (cleared by ending)"
1148 }
1149 line("blocked by", title(ref)+mark)
1150 }
1151 for _, other := range j.Blocks {
1152 line("blocks", title(other))
1153 }
1154 for _, other := range j.Children {
1155 line("child", title(other))
1156 }
1157 if j.Progress != nil {
1158 line("progress", fmt.Sprintf("%d of %d", j.Progress.Done, j.Progress.Of))
1159 }
1160 for _, c := range k.Changes {
1161 line("change", visible(c))
1162 }
1163 line("graduated", k.GraduatedInto)
1164 if j.Ready {
1165 b.WriteString("ready\n")
1166 }
1167 if k.Body != "" {
1168 b.WriteString("\n" + visible(k.Body))
1169 }
1170 for _, c := range s.graph.Comments[k.ID] {
1171 fmt.Fprintf(&b, "\n— %s, %s\n%s", visible(c.Author), c.At.Format("2006-01-02 15:04Z"), visible(c.Body))
1172 }
1173 _, err = io.WriteString(w, b.String())
1174 return err
1175}
1176
1177func knotList(r remote, a knotArgs, w io.Writer) error {
1178 if a.typ != "" {
1179 if _, ok := knot.TypeNamed(a.typ); !ok {
1180 return failure(fmt.Sprintf("%q is no type of knot; the types are %s", a.typ, strings.Join(knot.TypeNames(), ", ")))
1181 }
1182 }
1183 if a.status != "" && a.status != "active" && a.status != "terminal" && !anyStatus(a.status) {
1184 return failure(fmt.Sprintf("%q is no status; --status takes active, terminal, or one of %s", a.status, strings.Join(allStatuses(), ", ")))
1185 }
1186 s, err := r.read()
1187 if err != nil {
1188 return err
1189 }
1190 foreign := r.foreign(r.g)
1191 var list []*jsonKnot
1192 for _, id := range s.graph.IDs() {
1193 k := s.graph.Knots[id]
1194 switch {
1195 case a.typ != "" && k.Type != a.typ,
1196 a.owner != "" && k.Owner != a.owner,
1197 a.status == "active" && !k.Active(),
1198 a.status == "terminal" && k.Active(),
1199 a.status != "" && a.status != "active" && a.status != "terminal" && k.Status != a.status:
1200 continue
1201 }
1202 j := r.jsonKnot(s, k, false, foreign)
1203 if a.ready && !j.Ready {
1204 continue
1205 }
1206 list = append(list, j)
1207 }
1208 if a.json {
1209 if list == nil {
1210 list = []*jsonKnot{}
1211 }
1212 return writeKnotJSON(w, struct {
1213 Schema string `json:"schema"`
1214 Project string `json:"project"`
1215 Tip string `json:"tip"`
1216 Knots []*jsonKnot `json:"knots"`
1217 }{"valley-knots/v1", r.name, s.tip, list})
1218 }
1219 var b strings.Builder
1220 for _, j := range list {
1221 var notes []string
1222 if j.Claim != nil {
1223 notes = append(notes, "claimed by "+visible(j.Claim.By))
1224 }
1225 if len(j.WaitingOn) > 0 {
1226 notes = append(notes, "waits on "+strings.Join(j.WaitingOn, ", "))
1227 }
1228 if j.Ready {
1229 notes = append(notes, "ready")
1230 }
1231 note := ""
1232 if len(notes) > 0 {
1233 note = " [" + strings.Join(notes, "; ") + "]"
1234 }
1235 fmt.Fprintf(&b, "%-11s %-8s %-11s %s%s\n", j.ID, j.Type, j.Status, visible(j.Title), note)
1236 }
1237 _, err = io.WriteString(w, b.String())
1238 return err
1239}
1240
1241func anyStatus(s string) bool { return slices.Contains(allStatuses(), s) }
1242
1243func allStatuses() []string {
1244 var all []string
1245 for _, t := range knot.Types {
1246 for _, s := range t.Statuses() {
1247 if !slices.Contains(all, s) {
1248 all = append(all, s)
1249 }
1250 }
1251 }
1252 return all
1253}
1254
1255func age(seconds int64) string {
1256 d := time.Duration(seconds) * time.Second
1257 switch {
1258 case d < time.Hour:
1259 return fmt.Sprintf("%dm", int(d.Minutes()))
1260 case d < 48*time.Hour:
1261 return fmt.Sprintf("%dh", int(d.Hours()))
1262 }
1263 return fmt.Sprintf("%dd", int(d.Hours()/24))
1264}
1265
1266// visible is text made safe to print to a terminal: every control
1267// character but newline and tab, and every character that reorders the
1268// text around it, is written as an escape instead. The graph refuses
1269// control characters, so this is a second guard rather than the first.
1270func visible(s string) string {
1271 var b strings.Builder
1272 for _, r := range s {
1273 if r != '\n' && r != '\t' && (unicode.IsControl(r) || unicode.Is(unicode.Bidi_Control, r)) {
1274 fmt.Fprintf(&b, "\\u{%04x}", r)
1275 continue
1276 }
1277 b.WriteRune(r)
1278 }
1279 return b.String()
1280}
1281
1282// writeKnotJSON prints one indented JSON document.
1283func writeKnotJSON(w io.Writer, v any) error {
1284 enc := json.NewEncoder(w)
1285 enc.SetEscapeHTML(false)
1286 enc.SetIndent("", " ")
1287 return enc.Encode(v)
1288}