gunk-dev/the-valley

list.go

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