gunk-dev/the-valley

list.go

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