gunk-dev/the-valley

list.go

source6efad60d7fa5main's published tip history
17.1 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 := g.output(false, "ls-remote", "origin", "refs/heads/"+recordTarget)
195 if err != nil {
196 return "", nil, errors.New("could not read origin")
197 }
198 tip, _, _ = strings.Cut(tip, "\t")
199 if tip == "" {
200 return "", nil, errors.New("origin has no main branch to read policy/valley from")
201 }
202 if err := fetch(g, tip); err != nil {
203 return "", nil, err
204 }
205 if pointer, err := g.output(true, "cat-file", "blob", tip+":"+valleyPointer); err == nil {
206 instance = pointerURL(pointer)
207 if instance == "" {
208 return "", nil, fmt.Errorf("%s on main names no repository", valleyPointer)
209 }
210 } else if g.succeeds(true, "cat-file", "-e", tip+":"+instanceLayer) {
211 instance, _ = g.output(true, "remote", "get-url", "origin")
212 } else {
213 return "", nil, fmt.Errorf("main on origin names no owning valley at %s", valleyPointer)
214 }
215 line, err := g.output(false, "ls-remote", instance, projectsRef)
216 if err != nil {
217 return instance, nil, fmt.Errorf("could not read the instance repository %s", instance)
218 }
219 oid, ref, _ := strings.Cut(line, "\t")
220 if ref != projectsRef {
221 return instance, nil, fmt.Errorf("the instance repository %s publishes no %s", instance, projectsRef)
222 }
223 if !g.succeeds(true, "cat-file", "-e", oid) {
224 if _, err := g.output(false, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", instance, oid); err != nil {
225 return instance, nil, fmt.Errorf("could not fetch %s from %s", projectsRef, instance)
226 }
227 }
228 list, err := g.output(true, "cat-file", "blob", oid)
229 if err != nil {
230 return instance, nil, fmt.Errorf("%s in %s is not a list of projects", projectsRef, instance)
231 }
232 for _, name := range strings.Split(list, "\n") {
233 if name == "" {
234 continue
235 }
236 if !change.ValidPrincipal(name) {
237 return instance, nil, fmt.Errorf("%s in %s lists %q, which is not a project name", projectsRef, instance, name)
238 }
239 names = append(names, name)
240 }
241 sort.Strings(names)
242 return instance, names, nil
243}
244
245// pointerURL is the first line of policy/valley that is neither blank nor
246// a comment, as bin/valley's pointer_url reads it.
247func pointerURL(pointer string) string {
248 for _, line := range strings.Split(pointer, "\n") {
249 line, _, _ = strings.Cut(line, "#")
250 if line = strings.TrimSpace(line); line != "" {
251 return line
252 }
253 }
254 return ""
255}
256
257// projectURL is the URL of a project served beside the instance
258// repository: the instance's URL with its last path segment replaced by
259// the project's name. A segment ending in .git gives a name ending in .git.
260// It reads every form git fetch takes: a URL with a scheme, the scp-like
261// [user@]host:path, and a local path.
262func projectURL(instance, name string) (string, error) {
263 u := strings.TrimRight(instance, "/")
264 start := 0 // where the path begins
265 if scheme := strings.Index(u, "://"); scheme >= 0 {
266 slash := strings.Index(u[scheme+3:], "/")
267 if slash < 0 {
268 return "", fmt.Errorf("the instance URL %s has no path to replace", instance)
269 }
270 start = scheme + 3 + slash
271 } else if colon := strings.Index(u, ":"); colon >= 0 && !strings.Contains(u[:colon], "/") {
272 start = colon + 1
273 }
274 cut := start + strings.LastIndex(u[start:], "/") + 1
275 segment := u[cut:]
276 if segment == "" || segment == ".git" {
277 return "", fmt.Errorf("the instance URL %s has no path to replace", instance)
278 }
279 if strings.HasSuffix(segment, ".git") {
280 name += ".git"
281 }
282 return u[:cut] + name, nil
283}
284
285// hostOf is the host a URL reaches, with its port when one is given and
286// without its user. A local path reaches localhost.
287func hostOf(url string) string {
288 if scheme := strings.Index(url, "://"); scheme >= 0 {
289 rest := url[scheme+3:]
290 rest, _, _ = strings.Cut(rest, "/")
291 if at := strings.LastIndex(rest, "@"); at >= 0 {
292 rest = rest[at+1:]
293 }
294 if rest == "" {
295 return "localhost"
296 }
297 return rest
298 }
299 if colon := strings.Index(url, ":"); colon >= 0 && !strings.Contains(url[:colon], "/") {
300 host := url[:colon]
301 if at := strings.LastIndex(host, "@"); at >= 0 {
302 host = host[at+1:]
303 }
304 return host
305 }
306 return "localhost"
307}
308
309// cacheRepo is the clone a repository other than the current one is read
310// through: a repository under $XDG_CACHE_HOME/valley/repos, keyed by its
311// URL, with origin set to it. It holds no checkout. Only fetches by object
312// ID write to it, and main's tip is kept at refs/remotes/origin/main so
313// valley checks can be run inside it.
314func cacheRepo(g git, url, name string) (git, error) {
315 base := os.Getenv("XDG_CACHE_HOME")
316 if base == "" {
317 home, err := os.UserHomeDir()
318 if err != nil {
319 return git{}, errors.New("no cache directory to read other repositories through")
320 }
321 base = filepath.Join(home, ".cache")
322 }
323 sum := sha256.Sum256([]byte(url))
324 dir := filepath.Join(base, "valley", "repos", hex.EncodeToString(sum[:8])+"-"+name)
325 c := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: dir}
326 if _, err := os.Stat(filepath.Join(dir, ".git")); err != nil {
327 if err := os.MkdirAll(dir, 0o755); err != nil {
328 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
329 }
330 if _, err := c.output(false, "init", "--quiet"); err != nil {
331 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
332 }
333 if _, err := c.output(false, "remote", "add", "origin", url); err != nil {
334 return git{}, fmt.Errorf("could not set origin in %s", dir)
335 }
336 }
337 return c, nil
338}
339
340// cacheEnvironment is env without the variables that would point git at
341// another repository than the cache's.
342func cacheEnvironment(env []string) []string {
343 var kept []string
344 for _, kv := range env {
345 name, _, _ := strings.Cut(kv, "=")
346 switch name {
347 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX", "GIT_NAMESPACE":
348 continue
349 }
350 kept = append(kept, kv)
351 }
352 return kept
353}
354
355// listed is one repository as read: its snapshot, or the error that kept
356// it from being read.
357type listed struct {
358 source
359 snap *snapshot
360}
361
362// readSources reads every source. A repository that cannot be read is
363// listed with its error, and the rest are listed all the same.
364func readSources(list []source, v verifier) []listed {
365 var out []listed
366 for _, s := range list {
367 l := listed{source: s}
368 if s.err == nil {
369 l.snap, l.err = readSnapshot(s.g, v)
370 if l.err != nil && s.g.dir != "" {
371 l.err = fmt.Errorf("could not read %s", s.url)
372 }
373 }
374 if l.err == nil && l.snap.tip != "" && l.g.dir != "" {
375 // The clone's main, for valley checks to read the policy at.
376 _, _ = l.g.output(true, "update-ref", "refs/remotes/origin/"+recordTarget, l.snap.tip)
377 }
378 out = append(out, l)
379 }
380 return out
381}
382
383// handles gives each change listed its handle among every change listed,
384// in every repository, so no two share one. Every record of a repository
385// is counted, listed or not, so a handle also names its change in that
386// repository alone.
387func handles(repos []listed) map[string]string {
388 var ids []string
389 for _, r := range repos {
390 if r.snap != nil {
391 for _, n := range r.snap.all {
392 ids = append(ids, n.id)
393 }
394 }
395 }
396 sort.Strings(ids)
397 h := map[string]string{}
398 for _, id := range ids {
399 h[id] = change.Handle(id, ids)
400 }
401 return h
402}
403
404// changeView is a change as valley-changes/v1 writes it, with includes
405// among the candidates given.
406func (s *snapshot) changeView(n recorded, handle string, candidates []recorded) jsonChange {
407 r := n.record
408 c := jsonChange{
409 ChangeID: n.id, Handle: handle, Target: r.Target, Owner: r.Owner, State: r.State,
410 Record: n.commit, Seq: r.Seq, Active: r.Active, Includes: s.includes(n, candidates),
411 }
412 for _, v := range r.Versions {
413 kind, commit := s.landing(n.id, v)
414 jv := jsonVersion{
415 N: v.N, Head: headOf(v), Title: v.Title, Branch: v.Branch, Uploader: v.Uploader,
416 Landing: kind, Request: s.request(n.id, v),
417 }
418 if commit != "" {
419 jv.LandedCommit = &commit
420 }
421 if _, m, ok := s.outcome(n.id, v); ok {
422 jv.Outcome = &versionOutcome{Decision: m.decision, Head: m.head}
423 if isObjectID(m.tip) {
424 tip := m.tip
425 jv.Outcome.Tip = &tip
426 }
427 }
428 c.Versions = append(c.Versions, jv)
429 }
430 return c
431}
432
433// repoView is a repository as valley-changes/v1 writes it, holding the
434// changes keep chooses, each with includes among those include chooses.
435func (l listed) repoView(h map[string]string, keep, include func(*snapshot, recorded) bool) jsonRepo {
436 r := jsonRepo{Repo: l.name, URL: l.url, Changes: []jsonChange{}, Branches: []jsonBranch{}}
437 if l.err != nil {
438 msg := l.err.Error()
439 r.Error = &msg
440 return r
441 }
442 var candidates []recorded
443 for _, n := range l.snap.all {
444 if include(l.snap, n) {
445 candidates = append(candidates, n)
446 }
447 }
448 for _, n := range l.snap.all {
449 if keep(l.snap, n) {
450 r.Changes = append(r.Changes, l.snap.changeView(n, h[n.id], candidates))
451 }
452 }
453 r.Branches = l.snap.unrecorded()
454 return r
455}
456
457func everyChange(*snapshot, recorded) bool { return true }
458
459// writeDocument writes a listing document as one line of JSON. Every
460// string in it must be UTF-8: encoding/json would write any other bytes
461// as U+FFFD, which is another string.
462func writeDocument(w io.Writer, doc jsonChanges) error {
463 bad := false
464 walkStrings(doc, func(s string) { bad = bad || !utf8.ValidString(s) })
465 if bad {
466 return failure("a name in the listing is not UTF-8, so JSON cannot carry it")
467 }
468 var buf bytes.Buffer
469 enc := json.NewEncoder(&buf)
470 enc.SetEscapeHTML(false)
471 if err := enc.Encode(doc); err != nil {
472 return err
473 }
474 _, err := w.Write(buf.Bytes())
475 return err
476}
477
478// walkStrings calls f with every string a listing document holds.
479func walkStrings(doc any, f func(string)) {
480 switch d := doc.(type) {
481 case jsonChanges:
482 f(d.Schema)
483 f(d.Host)
484 for _, r := range d.Repos {
485 walkStrings(r, f)
486 }
487 case jsonRepo:
488 f(d.Repo)
489 f(d.URL)
490 if d.Error != nil {
491 f(*d.Error)
492 }
493 for _, c := range d.Changes {
494 f(c.ChangeID)
495 f(c.Handle)
496 f(c.Target)
497 f(c.Owner)
498 f(c.State)
499 for _, v := range c.Versions {
500 f(v.Title)
501 f(v.Branch)
502 f(v.Uploader)
503 }
504 }
505 for _, b := range d.Branches {
506 f(b.Branch)
507 }
508 }
509}
510
511// utf8Branches drops every branch whose name is not UTF-8 from a listing,
512// and says so on stderr: JSON cannot carry such a name exactly.
513func utf8Branches(r *jsonRepo, stderr io.Writer) {
514 kept := r.Branches[:0]
515 for _, b := range r.Branches {
516 if !utf8.ValidString(b.Branch) {
517 fmt.Fprintf(stderr, "valley: %s: left out the branch %s, whose name is not UTF-8\n", r.Repo, shellQuote(b.Branch))
518 continue
519 }
520 kept = append(kept, b)
521 }
522 r.Branches = kept
523}
524
525func runChanges(g git, args []string, stdout, stderr io.Writer) error {
526 l, err := parseListing("changes", args, false)
527 if err != nil {
528 return err
529 }
530 if !l.asJSON {
531 return failure("changes prints valley-changes/v1 alone; pass --json. valley pending is the view to read")
532 }
533 list, host, err := sources(g, l, stderr)
534 if err != nil {
535 return err
536 }
537 repos := readSources(list, verifierFromEnv())
538 h := handles(repos)
539 doc := jsonChanges{Schema: changesSchema, Host: host, Repos: []jsonRepo{}}
540 for _, r := range repos {
541 view := r.repoView(h, everyChange, everyChange)
542 utf8Branches(&view, stderr)
543 doc.Repos = append(doc.Repos, view)
544 }
545 warnUnverified(repos, stderr)
546 return writeDocument(stdout, doc)
547}
548
549// warnUnverified says which repositories held a transfer statement that
550// could not be checked, so a landing there may be stronger than listed.
551func warnUnverified(repos []listed, stderr io.Writer) {
552 for _, r := range repos {
553 if r.snap != nil && r.snap.unverified {
554 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)
555 }
556 }
557}