gunk-dev/the-valley

list.go

source379aad7baef9main's published tip history
24.5 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. Fetches by object ID
426// write to it, and so does the check worker, which stores its attestation
427// refs there (worker.go). main's tip is kept at refs/remotes/origin/main so
428// valley checks can be run inside it.
429func cacheRepo(g git, url, name string) (git, error) {
430 base := os.Getenv("XDG_CACHE_HOME")
431 if base == "" {
432 home, err := os.UserHomeDir()
433 if err != nil {
434 return git{}, errors.New("no cache directory to read other repositories through")
435 }
436 base = filepath.Join(home, ".cache")
437 }
438 sum := sha256.Sum256([]byte(url))
439 dir := filepath.Join(base, "valley", "repos", hex.EncodeToString(sum[:8])+"-"+name)
440 c := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: dir}
441 if c.cacheComplete(url) {
442 return c, nil
443 }
444 // A clone is made whole in a directory of its own beside the cache's
445 // place, and renamed into place only then, so a run killed while it is
446 // made, git included, leaves no clone behind, only that directory. A
447 // clone already in the place that is not whole was left by an older
448 // version, and is set aside first.
449 parent := filepath.Dir(dir)
450 if err := os.MkdirAll(parent, 0o755); err != nil {
451 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
452 }
453 if _, err := os.Lstat(dir); err == nil {
454 aside, err := os.MkdirTemp(parent, "."+filepath.Base(dir)+".old-")
455 if err != nil || os.Rename(dir, filepath.Join(aside, "repo")) != nil {
456 return git{}, fmt.Errorf("could not set aside the incomplete cache repository %s", dir)
457 }
458 _ = os.RemoveAll(aside)
459 }
460 made, err := os.MkdirTemp(parent, "."+filepath.Base(dir)+".new-")
461 if err != nil {
462 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
463 }
464 defer os.RemoveAll(made) // gone once it is renamed into place
465 m := git{env: c.env, stderr: c.stderr, dir: made}
466 if _, err := m.output(false, "init", "--quiet"); err != nil {
467 return git{}, fmt.Errorf("could not make the cache repository %s", dir)
468 }
469 if _, err := m.output(false, "remote", "add", "--end-of-options", "origin", url); err != nil {
470 return git{}, fmt.Errorf("could not set origin in %s", dir)
471 }
472 if err := os.Rename(made, dir); err != nil && !c.cacheComplete(url) {
473 return git{}, fmt.Errorf("could not move the cache repository into %s", dir)
474 }
475 return c, nil
476}
477
478// cacheComplete reports whether the cache repository at c.dir is whole:
479// its configuration names url as origin. It reads the file and writes
480// nothing, so a lock a killed git left beside it does not stand in the
481// way.
482func (c git) cacheComplete(url string) bool {
483 got, err := c.output(true, "config", "--file", ".git/config", "--get", "remote.origin.url")
484 return err == nil && got == url
485}
486
487// cacheEnvironment is env without the variables that would point git at
488// another repository than the cache's, and with git held to
489// allowedProtocols.
490func cacheEnvironment(env []string) []string {
491 var kept []string
492 for _, kv := range env {
493 name, _, _ := strings.Cut(kv, "=")
494 switch name {
495 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX", "GIT_NAMESPACE":
496 continue
497 }
498 kept = append(kept, kv)
499 }
500 return append(kept, "GIT_ALLOW_PROTOCOL="+allowedProtocols)
501}
502
503// listed is one repository as read: its snapshot (or the error from reading
504// it) and the knots its plan graph links to its changes.
505type listed struct {
506 source
507 snap *snapshot
508 knots doers
509}
510
511// readSources reads every source. A repository that cannot be read is
512// listed with its error, and the rest are listed all the same.
513func readSources(list []source, v verifier) []listed {
514 var out []listed
515 for _, s := range list {
516 l := listed{source: s}
517 if s.err == nil {
518 l.snap, l.err = readSnapshot(s.g, v)
519 if l.err != nil && s.g.dir != "" {
520 l.err = fmt.Errorf("could not read %s", s.url)
521 }
522 }
523 if l.err == nil && l.snap.tip != "" && l.g.dir != "" {
524 // The clone's main, for valley checks to read the policy at.
525 _, _ = l.g.output(true, "update-ref", "refs/remotes/origin/"+recordTarget, l.snap.tip)
526 }
527 out = append(out, l)
528 }
529 return out
530}
531
532// readKnots reads the plan graph once for each readable repository in repos.
533func readKnots(repos []listed, verbose bool, stderr io.Writer) {
534 for i := range repos {
535 if repos[i].err == nil {
536 repos[i].knots = readDoers(repos[i].g, repos[i].name, verbose, stderr)
537 }
538 }
539}
540
541// handleKey names one change listed: changes are keyed by repository,
542// target and change ID.
543type handleKey struct{ repo, target, id string }
544
545// handleMap is the handle of each change listed.
546type handleMap map[handleKey]string
547
548// handles gives each change listed its handle among every change listed,
549// in every repository, so no two share one. Every record of a repository
550// is counted, listed or not, so a handle also names its change in that
551// repository alone. A change ID recorded in more than one repository
552// listed gets the handle <repo>:<prefix> in each, which every verb that
553// takes a handle reads in that repository. git refuses a colon in a ref
554// name, so a qualified handle is never also a branch's name.
555func handles(repos []listed) handleMap {
556 var ids []string
557 in := map[string]map[string]bool{} // change ID → the repositories recording it
558 for _, r := range repos {
559 if r.snap == nil {
560 continue
561 }
562 for _, n := range r.snap.all {
563 ids = append(ids, n.id)
564 if in[n.id] == nil {
565 in[n.id] = map[string]bool{}
566 }
567 in[n.id][r.name] = true
568 }
569 }
570 sort.Strings(ids)
571 h := handleMap{}
572 for _, r := range repos {
573 if r.snap == nil {
574 continue
575 }
576 for _, n := range r.snap.all {
577 handle := change.Handle(n.id, ids)
578 if len(in[n.id]) > 1 {
579 handle = r.name + ":" + handle
580 }
581 h[handleKey{r.name, n.record.Target, n.id}] = handle
582 }
583 }
584 return h
585}
586
587// changeView is a change as valley-changes/v1 writes it, with includes
588// among the candidates given.
589func (s *snapshot) changeView(n recorded, handle string, candidates []recorded) jsonChange {
590 r := n.record
591 c := jsonChange{
592 ChangeID: n.id, Handle: handle, Target: r.Target, Owner: r.Owner, State: r.State,
593 Record: n.commit, Seq: r.Seq, Active: r.Active, Includes: s.includes(n, candidates),
594 Restack: restackView(s.report(n.id)), Knots: []knotRef{},
595 }
596 for _, v := range r.Versions {
597 kind, commit := s.landing(n.id, v)
598 jv := jsonVersion{
599 N: v.N, Head: headOf(v), Title: v.Title, Branch: v.Branch, Uploader: v.Uploader,
600 Landing: kind, Request: s.request(n.id, v),
601 }
602 if commit != "" {
603 jv.LandedCommit = &commit
604 }
605 if _, m, ok := s.outcome(n.id, v); ok {
606 jv.Outcome = &versionOutcome{Decision: m.decision, Head: m.head}
607 if isObjectID(m.tip) {
608 tip := m.tip
609 jv.Outcome.Tip = &tip
610 }
611 }
612 c.Versions = append(c.Versions, jv)
613 }
614 return c
615}
616
617// repoView is a repository as valley-changes/v1 writes it, holding the
618// changes keep chooses, each with includes among those include chooses.
619func (l listed) repoView(h handleMap, keep, include func(*snapshot, recorded) bool) jsonRepo {
620 r := jsonRepo{Repo: l.name, URL: l.url, Changes: []jsonChange{}, Branches: []jsonBranch{}}
621 if l.err != nil {
622 msg := l.err.Error()
623 r.Error = &msg
624 return r
625 }
626 var candidates []recorded
627 for _, n := range l.snap.all {
628 if include(l.snap, n) {
629 candidates = append(candidates, n)
630 }
631 }
632 for _, n := range l.snap.all {
633 if keep(l.snap, n) {
634 c := l.snap.changeView(n, h[handleKey{l.name, n.record.Target, n.id}], candidates)
635 c.Knots = l.knots.of(n.id)
636 r.Changes = append(r.Changes, c)
637 }
638 }
639 r.Branches = l.snap.unrecorded()
640 return r
641}
642
643func everyChange(*snapshot, recorded) bool { return true }
644
645// writeDocument writes a listing document as one line of JSON. Every
646// string in it must be UTF-8: encoding/json would write any other bytes
647// as U+FFFD, which is another string.
648func writeDocument(w io.Writer, doc jsonChanges) error {
649 bad := false
650 walkStrings(doc, func(s string) { bad = bad || !utf8.ValidString(s) })
651 if bad {
652 return failure("a name in the listing is not UTF-8, so JSON cannot carry it")
653 }
654 var buf bytes.Buffer
655 enc := json.NewEncoder(&buf)
656 enc.SetEscapeHTML(false)
657 if err := enc.Encode(doc); err != nil {
658 return err
659 }
660 _, err := w.Write(buf.Bytes())
661 return err
662}
663
664// walkStrings calls f with every string a listing document holds.
665func walkStrings(doc any, f func(string)) {
666 switch d := doc.(type) {
667 case jsonChanges:
668 f(d.Schema)
669 f(d.Host)
670 for _, r := range d.Repos {
671 walkStrings(r, f)
672 }
673 case jsonRepo:
674 f(d.Repo)
675 f(d.URL)
676 if d.Error != nil {
677 f(*d.Error)
678 }
679 all := d.Changes
680 if d.Drafts != nil {
681 all = append(append([]jsonChange(nil), all...), *d.Drafts...)
682 }
683 for _, c := range all {
684 f(c.ChangeID)
685 f(c.Handle)
686 f(c.Target)
687 f(c.Owner)
688 f(c.State)
689 for _, k := range c.Knots {
690 f(k.ID)
691 f(k.Type)
692 f(k.Status)
693 f(k.Title)
694 }
695 for _, v := range c.Versions {
696 f(v.Title)
697 f(v.Branch)
698 f(v.Uploader)
699 }
700 }
701 for _, b := range d.Branches {
702 f(b.Branch)
703 }
704 }
705}
706
707// utf8Branches drops every branch whose name is not UTF-8 from a listing,
708// and says so on stderr: JSON cannot carry such a name exactly.
709func utf8Branches(r *jsonRepo, stderr io.Writer) {
710 kept := r.Branches[:0]
711 for _, b := range r.Branches {
712 if !utf8.ValidString(b.Branch) {
713 fmt.Fprintf(stderr, "valley: %s: left out the branch %s, whose name is not UTF-8\n", r.Repo, shellQuote(b.Branch))
714 continue
715 }
716 kept = append(kept, b)
717 }
718 r.Branches = kept
719}
720
721func runChanges(g git, args []string, stdout, stderr io.Writer) error {
722 l, err := parseListing("changes", args, false)
723 if err != nil {
724 return err
725 }
726 if !l.asJSON {
727 return failure("changes prints valley-changes/v1 alone; pass --json. valley pending is the view to read")
728 }
729 list, host, err := sources(g, l, stderr)
730 if err != nil {
731 return err
732 }
733 repos := readSources(list, newVerifier())
734 readKnots(repos, l.verbose, stderr)
735 h := handles(repos)
736 writeHandleCache(g, repos, h)
737 doc := jsonChanges{Schema: changesSchema, Host: host, Repos: []jsonRepo{}}
738 for _, r := range repos {
739 view := r.repoView(h, everyChange, everyChange)
740 utf8Branches(&view, stderr)
741 doc.Repos = append(doc.Repos, view)
742 }
743 warnUnverified(repos, stderr)
744 return writeDocument(stdout, doc)
745}
746
747// warnUnverified says which repositories held a transfer statement that
748// could not be checked, so a landing there may be stronger than listed,
749// and which records did not read, so are not listed.
750func warnUnverified(repos []listed, stderr io.Writer) {
751 for _, r := range repos {
752 if r.snap != nil {
753 for _, u := range r.snap.unread {
754 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)
755 }
756 }
757 if r.snap != nil && r.snap.unverified() {
758 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)
759 }
760 }
761}