gunk-dev/the-valley

list.go

source9067b6d5ac52main's published tip history
21.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 "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, checks bool
103 repo string
104}
105
106func parseListing(verb string, args []string, checks 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 == "--checks" && checks:
115 l.checks = 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 // The project and the instance share no history, so git warns
231 // "no common commits". The warning is kept for the error alone.
232 var diag bytes.Buffer
233 quiet := g
234 quiet.stderr = &diag
235 if _, err := quiet.output(false, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--end-of-options", instance, oid); err != nil {
236 msg := fmt.Sprintf("could not fetch %s from %s", projectsRef, instance)
237 if d := strings.TrimSpace(diag.String()); d != "" {
238 msg += ": " + d
239 }
240 return instance, nil, errors.New(msg)
241 }
242 }
243 list, err := g.output(true, "cat-file", "blob", oid)
244 if err != nil {
245 return instance, nil, fmt.Errorf("%s in %s is not a list of projects", projectsRef, instance)
246 }
247 for _, name := range strings.Split(list, "\n") {
248 if name == "" {
249 continue
250 }
251 if !change.ValidPrincipal(name) {
252 return instance, nil, fmt.Errorf("%s in %s lists %q, which is not a project name", projectsRef, instance, name)
253 }
254 names = append(names, name)
255 }
256 sort.Strings(names)
257 return instance, names, nil
258}
259
260// remoteRef is the object a remote's ref names, or "" when it has no such
261// ref. ls-remote matches a pattern against the tail of a ref name, so a
262// pushed refs/heads/x/refs/heads/main would match refs/heads/main too.
263// Each ref listed is compared whole.
264func remoteRef(g git, remote, ref string) (string, error) {
265 out, err := g.output(false, "ls-remote", "--end-of-options", remote, ref)
266 if err != nil {
267 return "", err
268 }
269 for _, line := range strings.Split(out, "\n") {
270 if oid, name, ok := strings.Cut(line, "\t"); ok && name == ref {
271 return oid, nil
272 }
273 }
274 return "", nil
275}
276
277// allowedProtocols are the transports git may use for a URL this command
278// derives from data: ssh, git, https, and file, which covers local paths.
279// GIT_ALLOW_PROTOCOL overrides any protocol.*.allow the caller's
280// configuration sets.
281const allowedProtocols = "ssh:git:https:file"
282
283// restricted is g with git held to allowedProtocols.
284func (g git) restricted() git {
285 g.env = append(append([]string(nil), g.env...), "GIT_ALLOW_PROTOCOL="+allowedProtocols)
286 return g
287}
288
289// checkURL refuses a URL that is unsafe to hand git when it comes from data
290// (policy/valley, or a name the host lists): one that opens with a dash,
291// which git would read as an option; a <transport>::<address> form, such
292// as ext::, which runs a remote helper or a command; and a URL with a
293// scheme other than ssh, git, https or file. A scp-like [user@]host:path
294// and a local path are allowed, but not with a host that opens with a
295// dash, which ssh would read as an option.
296func checkURL(u string) error {
297 switch {
298 case u == "":
299 return errors.New("no URL")
300 case strings.HasPrefix(u, "-"):
301 return fmt.Errorf("the URL %q opens with a dash, which git would read as an option", u)
302 case strings.ContainsFunc(u, func(r rune) bool { return r < 0x20 || r == 0x7f }):
303 return fmt.Errorf("the URL %q holds a control character", u)
304 case strings.HasPrefix(hostOf(u), "-"):
305 return fmt.Errorf("the URL %q names a host that opens with a dash", u)
306 }
307 if helper, _, ok := strings.Cut(u, "::"); ok && transportName.MatchString(helper) {
308 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)
309 }
310 if scheme, _, ok := strings.Cut(u, "://"); ok {
311 switch scheme {
312 case "ssh", "git", "https", "file":
313 default:
314 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)
315 }
316 }
317 return nil
318}
319
320// transportName is the shape of the transport in git's
321// <transport>::<address> form.
322var transportName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9+.-]*$`)
323
324// pointerURL is the first line of policy/valley that is neither blank nor
325// a comment, as bin/valley's pointer_url reads it.
326func pointerURL(pointer string) string {
327 for _, line := range strings.Split(pointer, "\n") {
328 line, _, _ = strings.Cut(line, "#")
329 if line = strings.TrimSpace(line); line != "" {
330 return line
331 }
332 }
333 return ""
334}
335
336// projectURL is the URL of a project served beside the instance
337// repository: the instance's URL with its last path segment replaced by
338// the project's name. A segment ending in .git gives a name ending in .git.
339// It reads every form git fetch takes: a URL with a scheme, the scp-like
340// [user@]host:path, and a local path.
341func projectURL(instance, name string) (string, error) {
342 u := strings.TrimRight(instance, "/")
343 start := 0 // where the path begins
344 if scheme := strings.Index(u, "://"); scheme >= 0 {
345 slash := strings.Index(u[scheme+3:], "/")
346 if slash < 0 {
347 return "", fmt.Errorf("the instance URL %s has no path to replace", instance)
348 }
349 start = scheme + 3 + slash
350 } else if colon := strings.Index(u, ":"); colon >= 0 && !strings.Contains(u[:colon], "/") {
351 start = colon + 1
352 }
353 cut := start + strings.LastIndex(u[start:], "/") + 1
354 segment := u[cut:]
355 if segment == "" || segment == ".git" {
356 return "", fmt.Errorf("the instance URL %s has no path to replace", instance)
357 }
358 if strings.HasSuffix(segment, ".git") {
359 name += ".git"
360 }
361 url := u[:cut] + name
362 return url, checkURL(url)
363}
364
365// hostOf is the host a URL reaches, with its port when one is given and
366// without its user. A local path reaches localhost.
367func hostOf(url string) string {
368 if scheme := strings.Index(url, "://"); scheme >= 0 {
369 rest := url[scheme+3:]
370 rest, _, _ = strings.Cut(rest, "/")
371 if at := strings.LastIndex(rest, "@"); at >= 0 {
372 rest = rest[at+1:]
373 }
374 if rest == "" {
375 return "localhost"
376 }
377 return rest
378 }
379 if colon := strings.Index(url, ":"); colon >= 0 && !strings.Contains(url[:colon], "/") {
380 host := url[:colon]
381 if at := strings.LastIndex(host, "@"); at >= 0 {
382 host = host[at+1:]
383 }
384 return host
385 }
386 return "localhost"
387}
388
389// cacheRepo is the clone a repository other than the current one is read
390// through: a repository under $XDG_CACHE_HOME/valley/repos, keyed by its
391// URL, with origin set to it. It holds no checkout. Only fetches by object
392// ID write to it, and main's tip is kept at refs/remotes/origin/main so
393// valley checks can be run inside it.
394func cacheRepo(g git, url, name string) (git, error) {
395 base := os.Getenv("XDG_CACHE_HOME")
396 if base == "" {
397 home, err := os.UserHomeDir()
398 if err != nil {
399 return git{}, errors.New("no cache directory to read other repositories through")
400 }
401 base = filepath.Join(home, ".cache")
402 }
403 sum := sha256.Sum256([]byte(url))
404 dir := filepath.Join(base, "valley", "repos", hex.EncodeToString(sum[:8])+"-"+name)
405 c := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: dir}
406 if _, err := os.Stat(filepath.Join(dir, ".git")); err != nil {
407 if err := os.MkdirAll(dir, 0o755); err != nil {
408 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
409 }
410 if _, err := c.output(false, "init", "--quiet"); err != nil {
411 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
412 }
413 if _, err := c.output(false, "remote", "add", "--end-of-options", "origin", url); err != nil {
414 return git{}, fmt.Errorf("could not set origin in %s", dir)
415 }
416 }
417 return c, nil
418}
419
420// cacheEnvironment is env without the variables that would point git at
421// another repository than the cache's, and with git held to
422// allowedProtocols.
423func cacheEnvironment(env []string) []string {
424 var kept []string
425 for _, kv := range env {
426 name, _, _ := strings.Cut(kv, "=")
427 switch name {
428 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX", "GIT_NAMESPACE":
429 continue
430 }
431 kept = append(kept, kv)
432 }
433 return append(kept, "GIT_ALLOW_PROTOCOL="+allowedProtocols)
434}
435
436// listed is one repository as read: its snapshot, or the error that kept
437// it from being read.
438type listed struct {
439 source
440 snap *snapshot
441}
442
443// readSources reads every source. A repository that cannot be read is
444// listed with its error, and the rest are listed all the same.
445func readSources(list []source, v verifier) []listed {
446 var out []listed
447 for _, s := range list {
448 l := listed{source: s}
449 if s.err == nil {
450 l.snap, l.err = readSnapshot(s.g, v)
451 if l.err != nil && s.g.dir != "" {
452 l.err = fmt.Errorf("could not read %s", s.url)
453 }
454 }
455 if l.err == nil && l.snap.tip != "" && l.g.dir != "" {
456 // The clone's main, for valley checks to read the policy at.
457 _, _ = l.g.output(true, "update-ref", "refs/remotes/origin/"+recordTarget, l.snap.tip)
458 }
459 out = append(out, l)
460 }
461 return out
462}
463
464// handleKey names one change listed: changes are keyed by repository,
465// target and change ID.
466type handleKey struct{ repo, target, id string }
467
468// handleMap is the handle of each change listed.
469type handleMap map[handleKey]string
470
471// handles gives each change listed its handle among every change listed,
472// in every repository, so no two share one. Every record of a repository
473// is counted, listed or not, so a handle also names its change in that
474// repository alone. A change ID recorded in more than one repository
475// listed gets the handle <repo>:<prefix> in each, which every verb that
476// takes a handle reads in that repository. git refuses a colon in a ref
477// name, so a qualified handle is never also a branch's name.
478func handles(repos []listed) handleMap {
479 var ids []string
480 in := map[string]map[string]bool{} // change ID → the repositories recording it
481 for _, r := range repos {
482 if r.snap == nil {
483 continue
484 }
485 for _, n := range r.snap.all {
486 ids = append(ids, n.id)
487 if in[n.id] == nil {
488 in[n.id] = map[string]bool{}
489 }
490 in[n.id][r.name] = true
491 }
492 }
493 sort.Strings(ids)
494 h := handleMap{}
495 for _, r := range repos {
496 if r.snap == nil {
497 continue
498 }
499 for _, n := range r.snap.all {
500 handle := change.Handle(n.id, ids)
501 if len(in[n.id]) > 1 {
502 handle = r.name + ":" + handle
503 }
504 h[handleKey{r.name, n.record.Target, n.id}] = handle
505 }
506 }
507 return h
508}
509
510// changeView is a change as valley-changes/v1 writes it, with includes
511// among the candidates given.
512func (s *snapshot) changeView(n recorded, handle string, candidates []recorded) jsonChange {
513 r := n.record
514 c := jsonChange{
515 ChangeID: n.id, Handle: handle, Target: r.Target, Owner: r.Owner, State: r.State,
516 Record: n.commit, Seq: r.Seq, Active: r.Active, Includes: s.includes(n, candidates),
517 }
518 for _, v := range r.Versions {
519 kind, commit := s.landing(n.id, v)
520 jv := jsonVersion{
521 N: v.N, Head: headOf(v), Title: v.Title, Branch: v.Branch, Uploader: v.Uploader,
522 Landing: kind, Request: s.request(n.id, v),
523 }
524 if commit != "" {
525 jv.LandedCommit = &commit
526 }
527 if _, m, ok := s.outcome(n.id, v); ok {
528 jv.Outcome = &versionOutcome{Decision: m.decision, Head: m.head}
529 if isObjectID(m.tip) {
530 tip := m.tip
531 jv.Outcome.Tip = &tip
532 }
533 }
534 c.Versions = append(c.Versions, jv)
535 }
536 return c
537}
538
539// repoView is a repository as valley-changes/v1 writes it, holding the
540// changes keep chooses, each with includes among those include chooses.
541func (l listed) repoView(h handleMap, keep, include func(*snapshot, recorded) bool) jsonRepo {
542 r := jsonRepo{Repo: l.name, URL: l.url, Changes: []jsonChange{}, Branches: []jsonBranch{}}
543 if l.err != nil {
544 msg := l.err.Error()
545 r.Error = &msg
546 return r
547 }
548 var candidates []recorded
549 for _, n := range l.snap.all {
550 if include(l.snap, n) {
551 candidates = append(candidates, n)
552 }
553 }
554 for _, n := range l.snap.all {
555 if keep(l.snap, n) {
556 r.Changes = append(r.Changes, l.snap.changeView(n, h[handleKey{l.name, n.record.Target, n.id}], candidates))
557 }
558 }
559 r.Branches = l.snap.unrecorded()
560 return r
561}
562
563func everyChange(*snapshot, recorded) bool { return true }
564
565// writeDocument writes a listing document as one line of JSON. Every
566// string in it must be UTF-8: encoding/json would write any other bytes
567// as U+FFFD, which is another string.
568func writeDocument(w io.Writer, doc jsonChanges) error {
569 bad := false
570 walkStrings(doc, func(s string) { bad = bad || !utf8.ValidString(s) })
571 if bad {
572 return failure("a name in the listing is not UTF-8, so JSON cannot carry it")
573 }
574 var buf bytes.Buffer
575 enc := json.NewEncoder(&buf)
576 enc.SetEscapeHTML(false)
577 if err := enc.Encode(doc); err != nil {
578 return err
579 }
580 _, err := w.Write(buf.Bytes())
581 return err
582}
583
584// walkStrings calls f with every string a listing document holds.
585func walkStrings(doc any, f func(string)) {
586 switch d := doc.(type) {
587 case jsonChanges:
588 f(d.Schema)
589 f(d.Host)
590 for _, r := range d.Repos {
591 walkStrings(r, f)
592 }
593 case jsonRepo:
594 f(d.Repo)
595 f(d.URL)
596 if d.Error != nil {
597 f(*d.Error)
598 }
599 all := d.Changes
600 if d.Drafts != nil {
601 all = append(append([]jsonChange(nil), all...), *d.Drafts...)
602 }
603 for _, c := range all {
604 f(c.ChangeID)
605 f(c.Handle)
606 f(c.Target)
607 f(c.Owner)
608 f(c.State)
609 for _, v := range c.Versions {
610 f(v.Title)
611 f(v.Branch)
612 f(v.Uploader)
613 }
614 }
615 for _, b := range d.Branches {
616 f(b.Branch)
617 }
618 }
619}
620
621// utf8Branches drops every branch whose name is not UTF-8 from a listing,
622// and says so on stderr: JSON cannot carry such a name exactly.
623func utf8Branches(r *jsonRepo, stderr io.Writer) {
624 kept := r.Branches[:0]
625 for _, b := range r.Branches {
626 if !utf8.ValidString(b.Branch) {
627 fmt.Fprintf(stderr, "valley: %s: left out the branch %s, whose name is not UTF-8\n", r.Repo, shellQuote(b.Branch))
628 continue
629 }
630 kept = append(kept, b)
631 }
632 r.Branches = kept
633}
634
635func runChanges(g git, args []string, stdout, stderr io.Writer) error {
636 l, err := parseListing("changes", args, false)
637 if err != nil {
638 return err
639 }
640 if !l.asJSON {
641 return failure("changes prints valley-changes/v1 alone; pass --json. valley pending is the view to read")
642 }
643 list, host, err := sources(g, l, stderr)
644 if err != nil {
645 return err
646 }
647 repos := readSources(list, verifierFromEnv())
648 h := handles(repos)
649 writeHandleCache(g, repos, h)
650 doc := jsonChanges{Schema: changesSchema, Host: host, Repos: []jsonRepo{}}
651 for _, r := range repos {
652 view := r.repoView(h, everyChange, everyChange)
653 utf8Branches(&view, stderr)
654 doc.Repos = append(doc.Repos, view)
655 }
656 warnUnverified(repos, stderr)
657 return writeDocument(stdout, doc)
658}
659
660// warnUnverified says which repositories held a transfer statement that
661// could not be checked, so a landing there may be stronger than listed,
662// and which records did not read, so are not listed.
663func warnUnverified(repos []listed, stderr io.Writer) {
664 for _, r := range repos {
665 if r.snap != nil {
666 for _, u := range r.snap.unread {
667 fmt.Fprintf(stderr, "valley: warning: %s: the change record %s does not read, so it is not listed: %s. The hook refuses such a record, so origin's storage is corrupt\n", r.name, u.ref, u.why)
668 }
669 }
670 if r.snap != nil && r.snap.unverified {
671 fmt.Fprintf(stderr, "valley: %s: a transfer statement could not be verified, so a change may have landed that is not listed so. %s\n", r.name, verifierHint)
672 }
673 }
674}