gunk-dev/the-valley

list.go

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