gunk-dev/the-valley

list.go

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