gunk-dev/the-valley

list.go

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