gunk-dev/the-valley

knot.go

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