gunk-dev/the-valley

bus.go

source6a7605f70901main's published tip history
4.2 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 // The directory is read from where the person is: git, given no
63 // repository's directory, runs at the top level of the checkout it
64 // is started in (at).
65 abs, err := filepath.Abs(dir)
66 if err != nil {
67 fmt.Fprintf(stderr, "valley: %s\n", err)
68 return 1
69 }
70 there := git{env: g.env, stderr: g.stderr, dir: abs}
71 in := func(args ...string) (string, error) {
72 return there.output(true, args...)
73 }
74 if _, err := in("rev-parse", "--git-dir"); err != nil {
75 fmt.Fprintf(stderr, "valley: not a git repository: %s\n", dir)
76 return 1
77 }
78 // The repository's name: its work tree's, or a bare repository's less
79 // .git, as the publisher hook names a repository a host serves.
80 bare, _ := in("rev-parse", "--is-bare-repository")
81 where := "--show-toplevel"
82 if bare == "true" {
83 where = "--absolute-git-dir"
84 }
85 top, err := in("rev-parse", where)
86 if err != nil {
87 fmt.Fprintf(stderr, "valley: not a git repository: %s\n", dir)
88 return 1
89 }
90 repo := filepath.Base(top)
91 if trimmed := strings.TrimSuffix(repo, ".git"); bare == "true" && trimmed != "" {
92 repo = trimmed
93 }
94 refs, err := in("for-each-ref", "--format=%(objectname) %(refname)")
95 if err != nil {
96 fmt.Fprintf(stderr, "valley: %s: could not list its refs: %s\n", dir, err)
97 return 1
98 }
99 count := 0
100 for _, line := range strings.Split(refs, "\n") {
101 oid, ref, ok := strings.Cut(line, " ")
102 if !ok {
103 continue
104 }
105 processStarted()
106 pub := exec.Command("nats", "pub", "valley.git."+repo+".ref-updated", refUpdated(repo, ref, oid))
107 pub.Stderr = stderr
108 if err := pub.Run(); err != nil {
109 return exitCode(err)
110 }
111 count++
112 }
113 fmt.Fprintf(stdout, "replayed %d refs of %s onto the bus\n", count, repo)
114 return 0
115}
116
117// refUpdated is the ref-updated event a push creating ref at oid in repo
118// publishes. The host's publisher hook (nix/valley-host.nix) builds the
119// same payload, and the integrator publishes a landing's (integrator/bus.go);
120// change one only with the others. A refname may hold ", which is
121// escaped as the hook escapes it, and < > &, which are written as they
122// are, as the hook writes them.
123func refUpdated(repo, ref, oid string) string {
124 var b bytes.Buffer
125 enc := json.NewEncoder(&b)
126 enc.SetEscapeHTML(false)
127 enc.Encode(struct {
128 Event string `json:"event"`
129 Repo string `json:"repo"`
130 Ref string `json:"ref"`
131 Old string `json:"old"`
132 New string `json:"new"`
133 }{"ref-updated", repo, ref, strings.Repeat("0", len(oid)), oid})
134 return strings.TrimSuffix(b.String(), "\n")
135}