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