gunk-dev/the-valley

list.go

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