gunk-dev/the-valley

main.go

source28abc5737165main's published tip history
27.7 KiB
1// integrator is the Phase 3 controller that lands changes by verifying
2// evidence (archive/design/roadmap.md). It is a single writer per target stream and
3// the commit point of dcr-439b771: it applies a change's delta to the
4// current tip, checks per required check that the contributor's evidence
5// still transfers, and either fast-forwards the protected ref or says which
6// checks need new evidence.
7//
8// It runs no check. Verification happens where a change is authored, and
9// the serialized section here is digest comparison and a ref write.
10package main
11
12import (
13 "the-valley/composed"
14 "the-valley/note"
15
16 "flag"
17 "fmt"
18 "io"
19 "os"
20 "os/exec"
21 "path/filepath"
22 "strconv"
23 "strings"
24 "syscall"
25 "time"
26)
27
28const usage = `usage: integrator <command> [flags]
29
30 reconcile judge every pending integration request once, and act
31 watch reconcile at start, when woken and on an interval,
32 until interrupted
33 publish-signers publish what clients verify transfer statements with
34 (integrator publish-signers --help)
35 help print this message
36
37The integrator level-triggers over refs. Integration requests are durable
38in git — refs/the-valley/integration-requests/<target>/<change>, whose
39commit is the change's head — and the bus is a projection over them, so
40each pass reads the refs as they are and converges. It publishes its
41outcomes to the bus and consumes nothing from it. What starts a pass is
42the start, the interval, and, given --woken-by, a mark in its own wake
43directory (see below). A mark only starts a pass: it carries nothing, and
44what a pass decides comes from the refs it reads.
45
46The commit rule (dcr-439b771). The delta must apply cleanly to the tip; a
47conflict is new authorship, so every check is re-demanded. Then, per check
48the policy requires: a pure check transfers when its input-closure digest
49recomputed on the landed tree equals the attested one, and an effectful
50check transfers while no intervening landing has touched its requiring
51class's paths and its observation is inside the validity window the policy
52declares. Anything left standing lands; anything invalidated surfaces as
53one request-stale event naming exactly those checks, and the request stays
54for approving again.
55
56Before the commit rule, the change records can refuse a request. A request
57named c-<change ID> is that change's, and lands only while the record at
58refs/the-valley/changes/<target>/<change ID> says ready and lists the
59request's head as one of its versions'. A request of any name does not land
60while any commit it brings is a version of a change whose record is not
61ready. Both refuse with refused-not-ready. A request whose commits from the
62merge base to the head include a merge is refused-merge. A refused request
63stays where it is, and is decided again on every pass, so a change readied
64again is judged on the next one. Every record is read again just before
65the target moves, and a record never makes a request land.
66
67A withdrawn change voids its requests: each pass deletes the requests named
68for it or at one of its version heads, as voided-withdrawn, so readying it
69again needs a fresh approval. A record that does not read refuses nothing,
70and is reported with a WARNING on every pass that reads records.
71
72flags:
73 --repo DIR the served repository (default: here)
74 --project NAME the project name events carry (default: the repo's)
75 --key PATH ed25519 private key the integrator signs with
76 --name NAME the name that key signs under (default: this host's)
77 --known-signers F verifier keys whose attestations count, one per line
78 --signer-projects F signers whose attestations count only in the projects
79 listed beside them (see below); read once, at start, so a
80 changed file counts from the next start
81 --instance-repo DIR the bare repository carrying the group's floor; the
82 instance layer is read from its integrated tip
83 --instance-ref REF the ref whose tip carries it, a full ref name read by
84 that exact name (default refs/heads/main)
85 --instance-policy P the floor's directory in that tip (default
86 policy/instance); a floor that is not there is refused
87 --instance DIR a materialized instance layer, for a host that serves
88 no instance repository; one of this or --instance-repo
89 --project-policy P the project policy layer, relative to the target tip
90 (default policy/project); a target that carries none
91 is judged under the floor alone
92 --schema FILE the verification schema
93 --attest-schema F the attestation schema
94 --event-schema F the event vocabulary payloads are vetted against
95 --bus URL nats server to publish outcomes to; empty publishes
96 nothing and still prints every payload
97 --publish-queue DIR the host's queue of ref moves to publish: each landing
98 leaves its target's move there, and the host pushes it
99 to the mirrors as it does a pushed one; empty leaves
100 nothing
101 --wake DIR the host check worker's wake directory: each landing
102 creates the empty file DIR/due, before the mirror
103 queue and the bus, so the worker starts a pass;
104 empty marks nothing. Output only; --woken-by is what
105 wakes this controller
106 --wake-floor-reader DIR
107 another controller's wake directory, which reads the
108 floor this one lands: each landing on --instance-ref
109 creates the empty file DIR/due, after the worker's
110 mark and before the mirror queue and the bus. Only the
111 controller serving --instance-repo takes it. Repeat it
112 for each reader
113 --woken-by DIR watch: this controller's own wake directory (Linux
114 only). A pass starts soon after a writer creates
115 DIR/due, and once more after any pass that lands
116 something; see below
117 --approval-signers F
118 the approval signers file the identity compiler
119 writes. The controller takes the path and reads
120 nothing from it; a file that is not there yet is
121 taken all the same
122 --approval-signers-hardware F
123 the hardware approval signers file the identity
124 compiler writes, taken the same way. A controller
125 given one absolute path for both refuses to start
126 --push-policy F the project's push policy, the file the pre-receive
127 hook reads, taken the same way
128 --system SYSTEM flake system for closure recomputation
129 --interval D watch: how long to wait after a pass before the next,
130 when nothing starts one sooner (default 15s)
131 --now TIME judge as at this RFC 3339 instant, for the effectful
132 window; defaults to the clock
133
134Every program the controller runs reads git with replacement refs off. A
135replacement ref makes one object stand in for another wherever git looks
136it up, so a pushed refs/replace/* could swap the floor, a project's policy
137or a change's tree without moving any ref the controller watches. No GIT_
138variable is inherited except the safe.directory entries of command-scope
139configuration, and system and user configuration are not read.
140
141--woken-by is how a controller starts a pass promptly. A writer that moves
142a ref the controller reads creates the empty file DIR/due with
143O_CREAT|O_EXCL, and a due already there is a mark already made. The
144controller watches DIR with inotify, removes due before a pass reads any
145ref, and starts the next pass when the pass ends if due is there again,
146so a mark made during a pass is never lost. While it watches DIR it holds
147a lock on DIR itself, so a second controller given the same DIR consumes
148no mark from it and passes at its interval. reconcile never reads DIR. The
149interval stays the recovery pass: a missed mark, a
150watch that failed and a missing directory are all covered by the next
151timer pass. A due that cannot be removed starts no pass until the next
152timer pass, and a pass that failed is followed by another no sooner than
15310s later. Each pass opens with the line "pass: REASON", where REASON is
154startup, due, timer, follow-up or watcher; a timer pass with nothing else
155to say prints nothing.
156
157One watch serves a repository at a time. watch takes an exclusive lock on
158the --repo directory before it sweeps its scratch or judges anything, and
159checks before every pass that the path still names the directory it
160locked. A second watch over the same repository stops at its start, and a
161watch whose repository path comes to name another directory stops. A
162reconcile run by hand takes no lock.
163
164--known-signers is the registry's interim compilation. Identity is a
165governed registry (dcr-b87f6e8) whose entries compile into what each
166enforcement boundary checks; no compiler exists yet, so the file is
167supplied directly and is exactly what dcr-b87f6e8 calls the first
168compilation's output. An attestation signed by nobody in it does not
169transfer, and that is reported per check rather than treated as a forgery.
170
171--signer-projects restricts signers to projects. Each line names a signer,
172then the projects its attestations count in, separated by spaces:
173
174 worker/attestations the-valley app
175
176A signer the file names counts only in the projects on its line, where the
177project is the name events carry. In any other project its attestations
178are reported as signed by no signer the integrator holds. A line with a
179name and no project lets that signer count nowhere. A signer the file does
180not name counts wherever the known-signers file lets it. Blank lines and
181lines that open with # are skipped. Every name and project is a word of
182printable ASCII. A file that cannot be read, names a signer twice, holds
183a word that is not printable ASCII, names a signer no verifier key can
184carry, or names the integrator's own --name stops the integrator before
185it judges anything.
186
187The integrator's own signature never makes a check's attestation count.
188It countersigns the attestations a landing carried, and that vouches for
189the landing; a countersigned attestation counts, in any project, only
190through another signer who counts there.
191`
192
193// integrator is one controller: which repository it serves, who it signs
194// as, whose evidence it accepts, and where it finds the policy.
195type integrator struct {
196 repo string
197 project string
198 out io.Writer
199 timings io.Writer // where timing lines go (timing.go); nil prints none
200 // sightings is when this process first saw each request, which timing
201 // lines report and nothing else reads (timing.go). Nil sees none.
202 sightings *sightings
203
204 // The programs it drives. Every judgement about a statement or a note
205 // is attest's, and cue composes the policy the integrator derives
206 // required checks from.
207 attest string
208 cue string
209 nats string
210
211 attestSchema string
212 eventSchema string
213 policy policySource
214
215 key string
216 signerName string
217 keyHash string
218 knownSigners string
219
220 // signerProjects restricts signers in knownSigners to projects
221 // (note/signerprojects.go). Nil restricts nobody. It is read once, at
222 // start, and signerProjectsData is the bytes it was read from, which
223 // the inputs digest covers (inputs.go).
224 signerProjects note.SignerProjects
225 signerProjectsData []byte
226
227 bus string
228 publishQueue string
229 wake string // the check worker's wake directory, or empty
230 system string
231
232 // approval holds the paths of the approval inputs. No pass reads
233 // them.
234 approval approvalInputs
235
236 // floorReaders are the wake directories of the controllers that read
237 // the floor this controller lands, marked after a landing on the
238 // floor's ref (bus.go). Empty for every controller but the instance
239 // repository's.
240 floorReaders []string
241
242 // landings counts the landings this process has made, so watch can
243 // tell a pass that landed something and follow it with another.
244 landings int
245
246 // clock, when set, is the instant the effectful window is measured
247 // against. Zero means the wall clock.
248 clock time.Time
249
250 // evidenceListed, when set, runs once collectEvidence has listed a
251 // subject's attestation refs, before it reads any of them. Tests set
252 // it to delete a ref in that window.
253 evidenceListed func()
254}
255
256func main() {
257 if len(os.Args) < 2 {
258 fmt.Fprint(os.Stderr, usage)
259 os.Exit(2)
260 }
261 // Before anything runs git, so that every git this process starts — its
262 // own and the ones attest starts — inherits the result.
263 os.Clearenv()
264 for _, kv := range gitEnvironment(environ) {
265 name, value, _ := strings.Cut(kv, "=")
266 os.Setenv(name, value)
267 }
268 var err error
269 switch os.Args[1] {
270 case "reconcile":
271 err = run(os.Args[2:], false)
272 case "watch":
273 err = run(os.Args[2:], true)
274 case "publish-signers":
275 err = publishSigners(os.Args[2:])
276 case "help", "-h", "--help":
277 fmt.Print(usage)
278 return
279 default:
280 fmt.Fprintf(os.Stderr, "integrator: unknown command %q\n\n%s", os.Args[1], usage)
281 os.Exit(2)
282 }
283 if err != nil {
284 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
285 os.Exit(1)
286 }
287}
288
289func run(args []string, loop bool) error {
290 fs := flag.NewFlagSet("integrator", flag.ExitOnError)
291 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
292 repo := fs.String("repo", ".", "the served repository")
293 project := fs.String("project", "", "the project name events carry")
294 key := fs.String("key", "", "ed25519 private key")
295 name := fs.String("name", defaultSignerName(), "the name that key signs under")
296 known := fs.String("known-signers", "", "verifier keys whose attestations count")
297 signerProjects := fs.String("signer-projects", "", "signers whose attestations count only in the projects listed beside them")
298 instanceRepo := fs.String("instance-repo", "", "the bare repository carrying the group's floor")
299 instanceRef := fs.String("instance-ref", "refs/heads/main", "the ref whose tip carries the floor")
300 instancePolicy := fs.String("instance-policy", "policy/instance", "the floor's directory in that tip")
301 instance := fs.String("instance", "", "a materialized instance policy layer")
302 projectPolicy := fs.String("project-policy", "policy/project", "the project policy layer, relative to the target tip")
303 schema := fs.String("schema", env("VALLEY_VERIFICATION_SCHEMA"), "the verification schema")
304 attestSchema := fs.String("attest-schema", env("VALLEY_ATTEST_SCHEMA"), "the attestation schema")
305 eventSchema := fs.String("event-schema", env("VALLEY_EVENT_SCHEMA"), "the event vocabulary")
306 bus := fs.String("bus", "", "nats server to publish outcomes to")
307 publishQueue := fs.String("publish-queue", "", "the host's queue of ref moves to publish")
308 wake := fs.String("wake", "", "the check worker's wake directory, marked due after each landing")
309 var floorReaders dirList
310 fs.Var(&floorReaders, "wake-floor-reader", "a floor-reading controller's wake directory, marked due after each floor landing")
311 wokenBy := fs.String("woken-by", "", "watch: this controller's own wake directory")
312 approvalSigners := fs.String("approval-signers", "", "the approval signers file the identity compiler writes")
313 approvalHardware := fs.String("approval-signers-hardware", "", "the hardware approval signers file the identity compiler writes")
314 pushPolicy := fs.String("push-policy", "", "the project's push policy, as the pre-receive hook reads it")
315 system := fs.String("system", "", "flake system")
316 interval := fs.Duration("interval", 15*time.Second, "how long to wait between passes")
317 now := fs.String("now", "", "judge as at this instant")
318 if err := fs.Parse(args); err != nil {
319 return err
320 }
321
322 in := &integrator{
323 repo: *repo,
324 project: *project,
325 out: os.Stdout,
326 timings: newDroppable(duplicate(syscall.Stdout, "stdout")),
327 sightings: newSightings(),
328 attestSchema: *attestSchema,
329 eventSchema: *eventSchema,
330 key: *key,
331 signerName: *name,
332 knownSigners: *known,
333 bus: *bus,
334 publishQueue: *publishQueue,
335 wake: *wake,
336 system: *system,
337 floorReaders: floorReaders,
338 }
339 for _, missing := range []struct{ flag, value string }{
340 {"--key", in.key},
341 {"--known-signers", in.knownSigners},
342 {"--schema", *schema},
343 {"--attest-schema", in.attestSchema},
344 } {
345 if missing.value == "" {
346 return fmt.Errorf("%s is required", missing.flag)
347 }
348 }
349 var err error
350 for _, tool := range []struct {
351 name string
352 into *string
353 }{{"attest", &in.attest}, {"cue", &in.cue}, {"nats", &in.nats}} {
354 if *tool.into, err = exec.LookPath(tool.name); err != nil && tool.name != "nats" {
355 return fmt.Errorf("%s is not on the path; the integrator drives it rather than reimplementing it", tool.name)
356 }
357 }
358 // The floor comes from the instance repository's integrated tip, or from
359 // a directory on disk, and never from both — two sources for one layer is
360 // a question about which one won every time the policy is read.
361 if (*instanceRepo == "") == (*instance == "") {
362 return fmt.Errorf("exactly one of --instance-repo and --instance is required: the floor is read from the instance repository's tip, or from a materialized directory for a host that serves none")
363 }
364 // abs of an empty path is the working directory, and an empty field is
365 // how the layer says which of its two sources it is.
366 layer := composed.Floor{Ref: *instanceRef, Dir: *instancePolicy}
367 if *instanceRepo != "" {
368 // A full ref name is read by that exact name. Any other name,
369 // such as main, git would resolve by trying several refs in
370 // turn, and a pusher can make one of them.
371 if !strings.HasPrefix(*instanceRef, "refs/") {
372 return fmt.Errorf("--instance-ref %s is not a full ref name; name it whole, as refs/heads/main", *instanceRef)
373 }
374 layer.Repo = abs(*instanceRepo)
375 } else {
376 layer.Path = abs(*instance)
377 }
378 in.policy = policySource{
379 schema: abs(*schema),
380 layer: layer,
381 projectDir: *projectPolicy,
382 cue: in.cue,
383 }
384 if *now != "" {
385 if in.clock, err = time.Parse(time.RFC3339, *now); err != nil {
386 return fmt.Errorf("--now: %w", err)
387 }
388 }
389 if in.repo, err = filepath.Abs(in.repo); err != nil {
390 return err
391 }
392 if in.project == "" {
393 in.project = projectName(in.repo)
394 }
395 if in.approval, err = newApprovalInputs(*approvalSigners, *approvalHardware, *pushPolicy); err != nil {
396 return err
397 }
398 if in.signerProjects, in.signerProjectsData, err = readSignerProjects(*signerProjects, in.signerName); err != nil {
399 return err
400 }
401 if in.keyHash, err = in.readKeyHash(); err != nil {
402 return err
403 }
404 if len(in.floorReaders) > 0 && !landsFloor(in.repo, layer) {
405 return fmt.Errorf("--wake-floor-reader is for the controller that lands the floor: give it only with --instance-repo naming the repository --repo serves")
406 }
407 // A wake directory is consumed by one long-lived controller. A
408 // reconcile run by hand beside it must not take its marks.
409 if *wokenBy != "" && !loop {
410 return fmt.Errorf("--woken-by is watch's: reconcile reads no wake directory")
411 }
412 if *wokenBy != "" && !wakeSupported {
413 return fmt.Errorf("--woken-by: watching a wake directory needs Linux's inotify; run watch without it to pass at --interval")
414 }
415 if loop && *interval <= 0 {
416 return fmt.Errorf("--interval %s: the recovery interval must be positive", *interval)
417 }
418
419 if !loop {
420 return in.reconcile(reasonOnce)
421 }
422 // Only the looping controller sweeps. A one-shot run may be somebody
423 // running the integrator by hand beside a controller that is already
424 // watching this repository, and sweeping from there would pull the
425 // worktree out from under a tick in progress.
426 //
427 // One controller serves a repository (own_unix.go). Its lock comes
428 // before the sweep, so a second watch over the same repository stops
429 // before it can sweep a worktree out from under the first, and the lock
430 // is checked again before every pass.
431 return serve(in.repo, sweepScratch, func(owned func() error) error {
432 if *wokenBy == "" {
433 for reason := reasonStartup; ; reason = reasonTimer {
434 if err := owned(); err != nil {
435 return err
436 }
437 if err := in.reconcile(reason); err != nil {
438 fmt.Fprintf(os.Stderr, "integrator: %v\n", err)
439 }
440 time.Sleep(*interval)
441 }
442 }
443 l := &wakeLoop{
444 dir: abs(*wokenBy),
445 interval: *interval,
446 stderr: os.Stderr,
447 watch: watchDir,
448 owned: owned,
449 pass: func(reason passReason) (bool, error) {
450 in.out = newPassOutput(os.Stdout, reason)
451 before := in.landings
452 err := in.reconcile(reason)
453 return in.landings > before, err
454 },
455 }
456 return l.run()
457 })
458}
459
460// serve is a watch's start: it takes the repository's lock, then sweeps
461// the repository's scratch, then runs the loop, which asks owned before
462// every pass. A watch that cannot take the lock does neither, and holds
463// nothing when it returns.
464func serve(repo string, sweep func(string), loop func(owned func() error) error) error {
465 owner, err := ownRepo(repo)
466 if err != nil {
467 return err
468 }
469 defer owner.Close()
470 sweep(repo)
471 return loop(owner.check)
472}
473
474// approvalInputs are the paths of the files that say who may approve and
475// how the project's refs take pushes: the two approval signers files the
476// identity compiler writes, and the project's push policy as the
477// pre-receive hook reads it. Each is absolute, or "" when it is not given.
478type approvalInputs struct {
479 signers, hardware, pushPolicy string
480}
481
482// newApprovalInputs takes the three paths without opening any of them, so
483// a file not written yet is taken as well as one that is. The two signers
484// files must be two files: one never stands in for the other.
485func newApprovalInputs(signers, hardware, pushPolicy string) (approvalInputs, error) {
486 a := approvalInputs{}
487 for _, p := range []struct {
488 into *string
489 value string
490 }{{&a.signers, signers}, {&a.hardware, hardware}, {&a.pushPolicy, pushPolicy}} {
491 if p.value != "" {
492 *p.into = abs(p.value)
493 }
494 }
495 if a.signers != "" && a.signers == a.hardware {
496 return approvalInputs{}, fmt.Errorf("--approval-signers and --approval-signers-hardware both name %s: they are two files, and one never stands in for the other", a.signers)
497 }
498 return a, nil
499}
500
501// dirList is a flag given once per directory.
502type dirList []string
503
504func (d *dirList) String() string { return strings.Join(*d, ",") }
505
506func (d *dirList) Set(dir string) error {
507 if dir == "" {
508 return fmt.Errorf("an empty directory marks nothing")
509 }
510 *d = append(*d, abs(dir))
511 return nil
512}
513
514// landsFloor says whether the repository this controller serves is the one
515// its floor is read from, so a landing there can move the floor.
516func landsFloor(repo string, layer composed.Floor) bool {
517 if layer.Repo == "" {
518 return false
519 }
520 a, err := os.Stat(repo)
521 if err != nil {
522 return false
523 }
524 b, err := os.Stat(layer.Repo)
525 return err == nil && os.SameFile(a, b)
526}
527
528// readKeyHash asks attest for the verifier key this integrator signs under,
529// and keeps the key hash: it is the segment that keeps one signer's
530// attestation ref from racing another's (dcr-0de694f).
531func (in *integrator) readKeyHash() (string, error) {
532 out, err := exec.Command(in.attest, "key", "--key", in.key, "--name", in.signerName).Output()
533 if err != nil {
534 return "", fmt.Errorf("reading the signing key: %w", err)
535 }
536 // name+hash+base64, split three ways: the name holds no plus and the
537 // base64 may.
538 fields := strings.SplitN(strings.TrimSpace(string(out)), "+", 3)
539 if len(fields) != 3 {
540 return "", fmt.Errorf("attest key printed %q", strings.TrimSpace(string(out)))
541 }
542 if _, err := strconv.ParseUint(fields[1], 16, 32); err != nil {
543 return "", fmt.Errorf("attest key printed the hash %q", fields[1])
544 }
545 return fields[1], nil
546}
547
548// projectName is the name the events carry: the repository's directory,
549// with a bare repo's .git suffix removed — the same name the post-receive
550// hook derives.
551func projectName(repo string) string {
552 if bare, err := gitLine(repo, "rev-parse", "--is-bare-repository"); err == nil && bare == "true" {
553 dir, _ := gitLine(repo, "rev-parse", "--absolute-git-dir")
554 return strings.TrimSuffix(filepath.Base(dir), ".git")
555 }
556 top, err := gitLine(repo, "rev-parse", "--show-toplevel")
557 if err != nil {
558 return filepath.Base(repo)
559 }
560 return filepath.Base(top)
561}
562
563// defaultSignerName is the name this machine signs under: its own name and
564// the suffix that keeps a key signing attestations distinct from the same
565// key signing anything else (dcr-de9d996).
566func defaultSignerName() string {
567 host, err := os.Hostname()
568 if err != nil || host == "" {
569 host = "localhost"
570 }
571 return host + "/attestations"
572}
573
574func env(name string) string { return os.Getenv(name) }
575
576// environ is the environment the process started with, read before main
577// replaces it.
578var environ = os.Environ()
579
580// gitEnvironment is the environment the controller runs in: the one it
581// started with, with git's part of it fixed.
582//
583// Replacement refs are off. A replacement ref makes one object stand in for
584// another wherever git looks it up, so a refs/replace/<blob> pushed to the
585// served repository or the instance repository could swap the floor, the
586// project's policy or a change's tree for anything its author liked,
587// without moving any ref the controller watches. Every judgement here reads
588// the repository's own objects.
589//
590// No other GIT_ variable is inherited, as sigverify inherits none: a GIT_DIR
591// or GIT_OBJECT_DIRECTORY could point git at other objects, and a
592// GIT_CONFIG_PARAMETERS could change how it reads them. System and user
593// configuration are not read either. The one thing kept is command-scope
594// configuration naming safe.directory, which is how the unit tells git it
595// may read repositories the controller does not own (nix/valley-host.nix).
596// Those entries are carried over, renumbered, and no other key is.
597func gitEnvironment(inherited []string) []string {
598 vars := map[string]string{}
599 var kept []string
600 for _, kv := range inherited {
601 name, value, _ := strings.Cut(kv, "=")
602 if strings.HasPrefix(name, "GIT_") {
603 vars[name] = value
604 continue
605 }
606 kept = append(kept, kv)
607 }
608
609 var safe []string
610 count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"])
611 for i := 0; i < count; i++ {
612 if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") {
613 safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)])
614 }
615 }
616 if len(safe) > 0 {
617 kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe)))
618 for i, dir := range safe {
619 kept = append(kept,
620 fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i),
621 fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir))
622 }
623 }
624
625 return append(kept,
626 "GIT_CONFIG_NOSYSTEM=1",
627 "GIT_CONFIG_SYSTEM=/dev/null",
628 "GIT_CONFIG_GLOBAL=/dev/null",
629 "GIT_NO_REPLACE_OBJECTS=1",
630 "GIT_ATTR_NOSYSTEM=1",
631 "GIT_TERMINAL_PROMPT=0",
632 )
633}
634
635func abs(path string) string {
636 if p, err := filepath.Abs(path); err == nil {
637 return p
638 }
639 return path
640}
641
642// gitEnv runs a git command with extra environment, for the one place the
643// integrator has to state who authored and who committed.
644func (in *integrator) gitEnv(extra map[string]string, args ...string) (string, error) {
645 cmd := exec.Command("git", args...)
646 cmd.Dir = in.repo
647 cmd.Env = os.Environ()
648 for k, v := range extra {
649 cmd.Env = append(cmd.Env, k+"="+v)
650 }
651 var errb strings.Builder
652 cmd.Stderr = &errb
653 out, err := cmd.Output()
654 if err != nil {
655 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
656 }
657 return string(out), nil
658}
659
660// writeTemp writes bytes to a file cue will read as JSON — the extension is
661// how cue tells a data file from a schema.
662func writeTemp(prefix string, body []byte) (string, error) {
663 dir, err := scratch(prefix)
664 if err != nil {
665 return "", err
666 }
667 path := filepath.Join(dir, "payload.json")
668 if err := os.WriteFile(path, body, 0o644); err != nil {
669 return "", err
670 }
671 return path, nil
672}
673
674func removeTemp(path string) { _ = os.RemoveAll(filepath.Dir(path)) }