gunk-dev/the-valley

list.go

source6f81ceede276main's published tip history
17.5 KiB
1// valley changes: every change, across every repository a host serves,
2// as valley-changes/v1. docs/architecture.md documents the object, and
3// klaus reads it, so a change to any field's name or meaning is a new
4// schema version.
5//
6// Without --all it lists the current repository. With --all it lists every
7// project the serving host publishes at refs/the-valley/projects in its
8// instance repository. The instance is found at policy/valley on main's
9// integrated tip, never in a checked-out or pushed tree, and each
10// project's URL is the instance's with its last path segment replaced, so
11// the transport, user and host are kept. A repository other than the
12// current one is read through a clone this command keeps under the user's
13// cache directory.
14
15package main
16
17import (
18 "bytes"
19 "crypto/sha256"
20 "encoding/hex"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io"
25 "os"
26 "path/filepath"
27 "sort"
28 "strings"
29 "unicode/utf8"
30
31 "the-valley/change"
32)
33
34const (
35 changesSchema = "valley-changes/v1"
36 pendingSchema = "valley-pending/v1"
37
38 projectsRef = "refs/the-valley/projects"
39 valleyPointer = "policy/valley"
40 instanceLayer = "policy/instance"
41)
42
43// The valley-changes/v1 object.
44type jsonChanges struct {
45 Schema string `json:"schema"`
46 Host string `json:"host"`
47 Repos []jsonRepo `json:"repos"`
48}
49
50type jsonRepo struct {
51 Repo string `json:"repo"`
52 URL string `json:"url"`
53 Error *string `json:"error"`
54 Changes []jsonChange `json:"changes"`
55 Branches []jsonBranch `json:"branches"`
56}
57
58type jsonChange struct {
59 ChangeID string `json:"change_id"`
60 Handle string `json:"handle"`
61 Target string `json:"target"`
62 Owner string `json:"owner"`
63 State string `json:"state"`
64 Record string `json:"record"`
65 Seq int `json:"seq"`
66 Active int `json:"active"`
67 Versions []jsonVersion `json:"versions"`
68 Includes []string `json:"includes"`
69}
70
71type jsonVersion struct {
72 N int `json:"n"`
73 Head string `json:"head"`
74 Title string `json:"title"`
75 Branch string `json:"branch"`
76 Uploader string `json:"uploader"`
77 Landing string `json:"landing"`
78 LandedCommit *string `json:"landed_commit"`
79 Request *jsonRequest `json:"request"`
80 Outcome *versionOutcome `json:"outcome"`
81}
82
83// versionOutcome is an outcome record about a version. Its head is the
84// version's head; its tip is given only when it is an object ID.
85type versionOutcome struct {
86 Decision string `json:"decision"`
87 Head string `json:"head"`
88 Tip *string `json:"tip"`
89}
90
91type jsonBranch struct {
92 Branch string `json:"branch"`
93 Head string `json:"head"`
94}
95
96// listing is what changes and pending were asked for.
97type listing struct {
98 asJSON, all, owes bool
99 repo string
100}
101
102func parseListing(verb string, args []string, owes bool) (listing, error) {
103 var l listing
104 for i := 0; i < len(args); i++ {
105 switch a := args[i]; {
106 case a == "--json":
107 l.asJSON = true
108 case a == "--all":
109 l.all = true
110 case a == "--owes" && owes:
111 l.owes = true
112 case a == "--repo" && i+1 < len(args):
113 i++
114 l.repo = args[i]
115 case strings.HasPrefix(a, "--repo="):
116 l.repo = strings.TrimPrefix(a, "--repo=")
117 default:
118 return l, failure(fmt.Sprintf("%s does not take %s", verb, a))
119 }
120 }
121 if l.repo != "" && !change.ValidPrincipal(l.repo) {
122 return l, failure(fmt.Sprintf("--repo %s: not a project name", l.repo))
123 }
124 return l, nil
125}
126
127// source is one repository to list: its name, its URL, and where it is
128// read, or why it could not be.
129type source struct {
130 name, url string
131 g git
132 err error
133}
134
135// sources are the repositories a listing covers, in name order, and the
136// host they are served from.
137func sources(g git, l listing, stderr io.Writer) ([]source, string, error) {
138 if !g.succeeds(true, "rev-parse", "--git-dir") {
139 return nil, "", failure("not a git repository")
140 }
141 originURL, err := g.output(true, "remote", "get-url", "origin")
142 if err != nil {
143 return nil, "", failure("this repository has no origin to read")
144 }
145 here := source{name: project(g), url: originURL, g: g}
146 if (!l.all && l.repo == "") || l.repo == here.name {
147 return []source{here}, hostOf(originURL), nil
148 }
149 instance, names, err := discover(g)
150 if err != nil && (l.repo == "" || instance == "") {
151 if l.repo != "" {
152 return nil, "", failure(fmt.Sprintf("cannot find %s: discovery is unavailable: %v", l.repo, err))
153 }
154 fmt.Fprintf(stderr, "valley: discovery is unavailable: %v; listing %s only\n", err, here.name)
155 return []source{here}, hostOf(originURL), nil
156 }
157 if l.repo != "" {
158 if names != nil && !contains(names, l.repo) {
159 return nil, "", failure(fmt.Sprintf("the host lists no project %s at %s", l.repo, projectsRef))
160 }
161 names = []string{l.repo}
162 }
163 var list []source
164 for _, name := range names {
165 if name == here.name {
166 list = append(list, here)
167 continue
168 }
169 url, err := projectURL(instance, name)
170 s := source{name: name, url: url, err: err}
171 if err == nil {
172 s.g, s.err = cacheRepo(g, url, name)
173 }
174 list = append(list, s)
175 }
176 return list, hostOf(instance), nil
177}
178
179func contains(list []string, s string) bool {
180 for _, x := range list {
181 if x == s {
182 return true
183 }
184 }
185 return false
186}
187
188// discover finds the serving host's instance repository and the projects
189// it publishes. The instance is named at policy/valley on main's tip on
190// origin, which is read fresh; a repository whose main carries
191// policy/instance is its own instance. On an error the instance is still
192// returned when it was found, with names nil.
193func discover(g git) (instance string, names []string, err error) {
194 tip, err := remoteRef(g, "origin", "refs/heads/"+recordTarget)
195 if err != nil {
196 return "", nil, errors.New("could not read origin")
197 }
198 if tip == "" {
199 return "", nil, errors.New("origin has no main branch to read policy/valley from")
200 }
201 if err := fetch(g, tip); err != nil {
202 return "", nil, err
203 }
204 if pointer, err := g.output(true, "cat-file", "blob", tip+":"+valleyPointer); err == nil {
205 instance = pointerURL(pointer)
206 if instance == "" {
207 return "", nil, fmt.Errorf("%s on main names no repository", valleyPointer)
208 }
209 } else if g.succeeds(true, "cat-file", "-e", tip+":"+instanceLayer) {
210 instance, _ = g.output(true, "remote", "get-url", "origin")
211 } else {
212 return "", nil, fmt.Errorf("main on origin names no owning valley at %s", valleyPointer)
213 }
214 oid, err := remoteRef(g, instance, projectsRef)
215 if err != nil {
216 return instance, nil, fmt.Errorf("could not read the instance repository %s", instance)
217 }
218 if oid == "" {
219 return instance, nil, fmt.Errorf("the instance repository %s publishes no %s", instance, projectsRef)
220 }
221 if !g.succeeds(true, "cat-file", "-e", oid) {
222 if _, err := g.output(false, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", instance, oid); err != nil {
223 return instance, nil, fmt.Errorf("could not fetch %s from %s", projectsRef, instance)
224 }
225 }
226 list, err := g.output(true, "cat-file", "blob", oid)
227 if err != nil {
228 return instance, nil, fmt.Errorf("%s in %s is not a list of projects", projectsRef, instance)
229 }
230 for _, name := range strings.Split(list, "\n") {
231 if name == "" {
232 continue
233 }
234 if !change.ValidPrincipal(name) {
235 return instance, nil, fmt.Errorf("%s in %s lists %q, which is not a project name", projectsRef, instance, name)
236 }
237 names = append(names, name)
238 }
239 sort.Strings(names)
240 return instance, names, nil
241}
242
243// remoteRef is the object a remote's ref names, or "" when it has no such
244// ref. ls-remote matches a pattern against the tail of a ref name, so a
245// pushed refs/heads/x/refs/heads/main would match refs/heads/main too.
246// Each ref listed is compared whole.
247func remoteRef(g git, remote, ref string) (string, error) {
248 out, err := g.output(false, "ls-remote", remote, ref)
249 if err != nil {
250 return "", err
251 }
252 for _, line := range strings.Split(out, "\n") {
253 if oid, name, ok := strings.Cut(line, "\t"); ok && name == ref {
254 return oid, nil
255 }
256 }
257 return "", nil
258}
259
260// pointerURL is the first line of policy/valley that is neither blank nor
261// a comment, as bin/valley's pointer_url reads it.
262func pointerURL(pointer string) string {
263 for _, line := range strings.Split(pointer, "\n") {
264 line, _, _ = strings.Cut(line, "#")
265 if line = strings.TrimSpace(line); line != "" {
266 return line
267 }
268 }
269 return ""
270}
271
272// projectURL is the URL of a project served beside the instance
273// repository: the instance's URL with its last path segment replaced by
274// the project's name. A segment ending in .git gives a name ending in .git.
275// It reads every form git fetch takes: a URL with a scheme, the scp-like
276// [user@]host:path, and a local path.
277func projectURL(instance, name string) (string, error) {
278 u := strings.TrimRight(instance, "/")
279 start := 0 // where the path begins
280 if scheme := strings.Index(u, "://"); scheme >= 0 {
281 slash := strings.Index(u[scheme+3:], "/")
282 if slash < 0 {
283 return "", fmt.Errorf("the instance URL %s has no path to replace", instance)
284 }
285 start = scheme + 3 + slash
286 } else if colon := strings.Index(u, ":"); colon >= 0 && !strings.Contains(u[:colon], "/") {
287 start = colon + 1
288 }
289 cut := start + strings.LastIndex(u[start:], "/") + 1
290 segment := u[cut:]
291 if segment == "" || segment == ".git" {
292 return "", fmt.Errorf("the instance URL %s has no path to replace", instance)
293 }
294 if strings.HasSuffix(segment, ".git") {
295 name += ".git"
296 }
297 return u[:cut] + name, nil
298}
299
300// hostOf is the host a URL reaches, with its port when one is given and
301// without its user. A local path reaches localhost.
302func hostOf(url string) string {
303 if scheme := strings.Index(url, "://"); scheme >= 0 {
304 rest := url[scheme+3:]
305 rest, _, _ = strings.Cut(rest, "/")
306 if at := strings.LastIndex(rest, "@"); at >= 0 {
307 rest = rest[at+1:]
308 }
309 if rest == "" {
310 return "localhost"
311 }
312 return rest
313 }
314 if colon := strings.Index(url, ":"); colon >= 0 && !strings.Contains(url[:colon], "/") {
315 host := url[:colon]
316 if at := strings.LastIndex(host, "@"); at >= 0 {
317 host = host[at+1:]
318 }
319 return host
320 }
321 return "localhost"
322}
323
324// cacheRepo is the clone a repository other than the current one is read
325// through: a repository under $XDG_CACHE_HOME/valley/repos, keyed by its
326// URL, with origin set to it. It holds no checkout. Only fetches by object
327// ID write to it, and main's tip is kept at refs/remotes/origin/main so
328// valley checks can be run inside it.
329func cacheRepo(g git, url, name string) (git, error) {
330 base := os.Getenv("XDG_CACHE_HOME")
331 if base == "" {
332 home, err := os.UserHomeDir()
333 if err != nil {
334 return git{}, errors.New("no cache directory to read other repositories through")
335 }
336 base = filepath.Join(home, ".cache")
337 }
338 sum := sha256.Sum256([]byte(url))
339 dir := filepath.Join(base, "valley", "repos", hex.EncodeToString(sum[:8])+"-"+name)
340 c := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: dir}
341 if _, err := os.Stat(filepath.Join(dir, ".git")); err != nil {
342 if err := os.MkdirAll(dir, 0o755); err != nil {
343 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
344 }
345 if _, err := c.output(false, "init", "--quiet"); err != nil {
346 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
347 }
348 if _, err := c.output(false, "remote", "add", "origin", url); err != nil {
349 return git{}, fmt.Errorf("could not set origin in %s", dir)
350 }
351 }
352 return c, nil
353}
354
355// cacheEnvironment is env without the variables that would point git at
356// another repository than the cache's.
357func cacheEnvironment(env []string) []string {
358 var kept []string
359 for _, kv := range env {
360 name, _, _ := strings.Cut(kv, "=")
361 switch name {
362 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX", "GIT_NAMESPACE":
363 continue
364 }
365 kept = append(kept, kv)
366 }
367 return kept
368}
369
370// listed is one repository as read: its snapshot, or the error that kept
371// it from being read.
372type listed struct {
373 source
374 snap *snapshot
375}
376
377// readSources reads every source. A repository that cannot be read is
378// listed with its error, and the rest are listed all the same.
379func readSources(list []source, v verifier) []listed {
380 var out []listed
381 for _, s := range list {
382 l := listed{source: s}
383 if s.err == nil {
384 l.snap, l.err = readSnapshot(s.g, v)
385 if l.err != nil && s.g.dir != "" {
386 l.err = fmt.Errorf("could not read %s", s.url)
387 }
388 }
389 if l.err == nil && l.snap.tip != "" && l.g.dir != "" {
390 // The clone's main, for valley checks to read the policy at.
391 _, _ = l.g.output(true, "update-ref", "refs/remotes/origin/"+recordTarget, l.snap.tip)
392 }
393 out = append(out, l)
394 }
395 return out
396}
397
398// handles gives each change listed its handle among every change listed,
399// in every repository, so no two share one. Every record of a repository
400// is counted, listed or not, so a handle also names its change in that
401// repository alone.
402func handles(repos []listed) map[string]string {
403 var ids []string
404 for _, r := range repos {
405 if r.snap != nil {
406 for _, n := range r.snap.all {
407 ids = append(ids, n.id)
408 }
409 }
410 }
411 sort.Strings(ids)
412 h := map[string]string{}
413 for _, id := range ids {
414 h[id] = change.Handle(id, ids)
415 }
416 return h
417}
418
419// changeView is a change as valley-changes/v1 writes it, with includes
420// among the candidates given.
421func (s *snapshot) changeView(n recorded, handle string, candidates []recorded) jsonChange {
422 r := n.record
423 c := jsonChange{
424 ChangeID: n.id, Handle: handle, Target: r.Target, Owner: r.Owner, State: r.State,
425 Record: n.commit, Seq: r.Seq, Active: r.Active, Includes: s.includes(n, candidates),
426 }
427 for _, v := range r.Versions {
428 kind, commit := s.landing(n.id, v)
429 jv := jsonVersion{
430 N: v.N, Head: headOf(v), Title: v.Title, Branch: v.Branch, Uploader: v.Uploader,
431 Landing: kind, Request: s.request(n.id, v),
432 }
433 if commit != "" {
434 jv.LandedCommit = &commit
435 }
436 if _, m, ok := s.outcome(n.id, v); ok {
437 jv.Outcome = &versionOutcome{Decision: m.decision, Head: m.head}
438 if isObjectID(m.tip) {
439 tip := m.tip
440 jv.Outcome.Tip = &tip
441 }
442 }
443 c.Versions = append(c.Versions, jv)
444 }
445 return c
446}
447
448// repoView is a repository as valley-changes/v1 writes it, holding the
449// changes keep chooses, each with includes among those include chooses.
450func (l listed) repoView(h map[string]string, keep, include func(*snapshot, recorded) bool) jsonRepo {
451 r := jsonRepo{Repo: l.name, URL: l.url, Changes: []jsonChange{}, Branches: []jsonBranch{}}
452 if l.err != nil {
453 msg := l.err.Error()
454 r.Error = &msg
455 return r
456 }
457 var candidates []recorded
458 for _, n := range l.snap.all {
459 if include(l.snap, n) {
460 candidates = append(candidates, n)
461 }
462 }
463 for _, n := range l.snap.all {
464 if keep(l.snap, n) {
465 r.Changes = append(r.Changes, l.snap.changeView(n, h[n.id], candidates))
466 }
467 }
468 r.Branches = l.snap.unrecorded()
469 return r
470}
471
472func everyChange(*snapshot, recorded) bool { return true }
473
474// writeDocument writes a listing document as one line of JSON. Every
475// string in it must be UTF-8: encoding/json would write any other bytes
476// as U+FFFD, which is another string.
477func writeDocument(w io.Writer, doc jsonChanges) error {
478 bad := false
479 walkStrings(doc, func(s string) { bad = bad || !utf8.ValidString(s) })
480 if bad {
481 return failure("a name in the listing is not UTF-8, so JSON cannot carry it")
482 }
483 var buf bytes.Buffer
484 enc := json.NewEncoder(&buf)
485 enc.SetEscapeHTML(false)
486 if err := enc.Encode(doc); err != nil {
487 return err
488 }
489 _, err := w.Write(buf.Bytes())
490 return err
491}
492
493// walkStrings calls f with every string a listing document holds.
494func walkStrings(doc any, f func(string)) {
495 switch d := doc.(type) {
496 case jsonChanges:
497 f(d.Schema)
498 f(d.Host)
499 for _, r := range d.Repos {
500 walkStrings(r, f)
501 }
502 case jsonRepo:
503 f(d.Repo)
504 f(d.URL)
505 if d.Error != nil {
506 f(*d.Error)
507 }
508 for _, c := range d.Changes {
509 f(c.ChangeID)
510 f(c.Handle)
511 f(c.Target)
512 f(c.Owner)
513 f(c.State)
514 for _, v := range c.Versions {
515 f(v.Title)
516 f(v.Branch)
517 f(v.Uploader)
518 }
519 }
520 for _, b := range d.Branches {
521 f(b.Branch)
522 }
523 }
524}
525
526// utf8Branches drops every branch whose name is not UTF-8 from a listing,
527// and says so on stderr: JSON cannot carry such a name exactly.
528func utf8Branches(r *jsonRepo, stderr io.Writer) {
529 kept := r.Branches[:0]
530 for _, b := range r.Branches {
531 if !utf8.ValidString(b.Branch) {
532 fmt.Fprintf(stderr, "valley: %s: left out the branch %s, whose name is not UTF-8\n", r.Repo, shellQuote(b.Branch))
533 continue
534 }
535 kept = append(kept, b)
536 }
537 r.Branches = kept
538}
539
540func runChanges(g git, args []string, stdout, stderr io.Writer) error {
541 l, err := parseListing("changes", args, false)
542 if err != nil {
543 return err
544 }
545 if !l.asJSON {
546 return failure("changes prints valley-changes/v1 alone; pass --json. valley pending is the view to read")
547 }
548 list, host, err := sources(g, l, stderr)
549 if err != nil {
550 return err
551 }
552 repos := readSources(list, verifierFromEnv())
553 h := handles(repos)
554 doc := jsonChanges{Schema: changesSchema, Host: host, Repos: []jsonRepo{}}
555 for _, r := range repos {
556 view := r.repoView(h, everyChange, everyChange)
557 utf8Branches(&view, stderr)
558 doc.Repos = append(doc.Repos, view)
559 }
560 warnUnverified(repos, stderr)
561 return writeDocument(stdout, doc)
562}
563
564// warnUnverified says which repositories held a transfer statement that
565// could not be checked, so a landing there may be stronger than listed.
566func warnUnverified(repos []listed, stderr io.Writer) {
567 for _, r := range repos {
568 if r.snap != nil && r.snap.unverified {
569 fmt.Fprintf(stderr, "valley: %s: a transfer statement could not be verified, so a change may have landed that is not listed so. Set VALLEY_KNOWN_SIGNERS to the known-signers file and VALLEY_INTEGRATOR_SIGNER to the integrator's signing name, with attest on PATH\n", r.name)
570 }
571 }
572}