gunk-dev/the-valley

knot.go

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