gunk-dev/the-valley

knot.go

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