gunk-dev/the-valley

bus.go

source6bf8ca46b311main's published tip history
3.9 KiB
1package main
2
3// valley tail and valley replay: thin verbs over the nats CLI, which
4// anyone with plain nats and git could do by hand. They are the only
5// verbs that need it.
6
7import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 "io"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "strings"
16 "syscall"
17)
18
19const needsNats = "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
20
21// runTail replaces this process with nats sub, on valley.> or the subject
22// given, so signals and the exit status are nats's own. The server comes
23// from the nats CLI's own config. It returns only when it could not start
24// nats.
25func runTail(args []string, stderr io.Writer) int {
26 if len(args) > 1 {
27 fmt.Fprintln(stderr, "valley: usage: valley tail [subject]")
28 return 1
29 }
30 nats, err := exec.LookPath("nats")
31 if err != nil {
32 fmt.Fprintf(stderr, "valley: %s\n", needsNats)
33 return 1
34 }
35 subject := "valley.>"
36 if len(args) == 1 && args[0] != "" {
37 subject = args[0]
38 }
39 err = syscall.Exec(nats, []string{"nats", "sub", subject}, os.Environ())
40 fmt.Fprintf(stderr, "valley: %s: %s\n", nats, err)
41 return 126
42}
43
44// runReplay publishes one ref-updated event per ref of the repository in
45// the directory given, the current one by default, from git for-each-ref
46// alone. A ref's prior value is not derivable from the repository, so old
47// is the all-zero ID: the payload a push creating the ref would produce.
48// A publish that fails ends the replay with nats's exit status.
49func runReplay(g git, args []string, stdout, stderr io.Writer) int {
50 if len(args) > 1 {
51 fmt.Fprintln(stderr, "valley: usage: valley replay [repo-dir]")
52 return 1
53 }
54 if _, err := exec.LookPath("nats"); err != nil {
55 fmt.Fprintf(stderr, "valley: %s\n", needsNats)
56 return 1
57 }
58 dir := "."
59 if len(args) == 1 && args[0] != "" {
60 dir = args[0]
61 }
62 in := func(args ...string) (string, error) {
63 return g.output(true, append([]string{"-C", dir}, args...)...)
64 }
65 if _, err := in("rev-parse", "--git-dir"); err != nil {
66 fmt.Fprintf(stderr, "valley: not a git repository: %s\n", dir)
67 return 1
68 }
69 // The repository's name: its work tree's, or a bare repository's less
70 // .git, as the publisher hook names a repository a host serves.
71 bare, _ := in("rev-parse", "--is-bare-repository")
72 where := "--show-toplevel"
73 if bare == "true" {
74 where = "--absolute-git-dir"
75 }
76 top, err := in("rev-parse", where)
77 if err != nil {
78 fmt.Fprintf(stderr, "valley: not a git repository: %s\n", dir)
79 return 1
80 }
81 repo := filepath.Base(top)
82 if trimmed := strings.TrimSuffix(repo, ".git"); bare == "true" && trimmed != "" {
83 repo = trimmed
84 }
85 refs, err := in("for-each-ref", "--format=%(objectname) %(refname)")
86 if err != nil {
87 fmt.Fprintf(stderr, "valley: %s: could not list its refs: %s\n", dir, err)
88 return 1
89 }
90 count := 0
91 for _, line := range strings.Split(refs, "\n") {
92 oid, ref, ok := strings.Cut(line, " ")
93 if !ok {
94 continue
95 }
96 processStarted()
97 pub := exec.Command("nats", "pub", "valley.git."+repo+".ref-updated", refUpdated(repo, ref, oid))
98 pub.Stderr = stderr
99 if err := pub.Run(); err != nil {
100 return exitCode(err)
101 }
102 count++
103 }
104 fmt.Fprintf(stdout, "replayed %d refs of %s onto the bus\n", count, repo)
105 return 0
106}
107
108// refUpdated is the ref-updated event a push creating ref at oid in repo
109// publishes. The host's publisher hook (nix/valley-host.nix) builds the
110// same payload, and the integrator publishes a landing's (integrator/bus.go);
111// change one only with the others. A refname may hold ", which is
112// escaped as the hook escapes it, and < > &, which are written as they
113// are, as the hook writes them.
114func refUpdated(repo, ref, oid string) string {
115 var b bytes.Buffer
116 enc := json.NewEncoder(&b)
117 enc.SetEscapeHTML(false)
118 enc.Encode(struct {
119 Event string `json:"event"`
120 Repo string `json:"repo"`
121 Ref string `json:"ref"`
122 Old string `json:"old"`
123 New string `json:"new"`
124 }{"ref-updated", repo, ref, strings.Repeat("0", len(oid)), oid})
125 return strings.TrimSuffix(b.String(), "\n")
126}