gunk-dev/the-valley

list.go

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