gunk-dev/the-valley

list.go

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