gunk-dev/the-valley

knot.go

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