gunk-dev/the-valley

list.go

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