gunk-dev/the-valley

list.go

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