gunk-dev/the-valley

state.go

source5ed515359461main's published tip history
2.3 KiB
1package main
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "io/fs"
8 "os"
9 "path/filepath"
10)
11
12// The state directory holds the scratch repository a pass reads origin
13// into, and what a pass keeps between passes. Two passes on one directory
14// would share the scratch repository and race each other's state, so a
15// pass locks the directory from start to end (lockState). And what a pass
16// keeps is about one repository's target, read and written as one
17// principal, so the directory belongs to those three, the first a pass
18// used it for (bindState).
19
20// The files in a state directory beside the scratch repository.
21const (
22 lockFile = "lock" // what a pass holds a lock on while it runs
23 bindingFile = "binding.json" // the repository, target and principal the directory belongs to
24)
25
26// binding is what a state directory belongs to: the repository as --repo
27// gave it, the target, and the principal.
28type binding struct {
29 Repository string `json:"repository"`
30 Target string `json:"target"`
31 Principal string `json:"principal"`
32}
33
34// bindState binds the state directory to b the first time a pass uses it,
35// and afterwards refuses a pass for anything else. It runs under the lock.
36func bindState(dir string, b binding) error {
37 path := filepath.Join(dir, bindingFile)
38 data, err := os.ReadFile(path)
39 switch {
40 case err == nil:
41 var was binding
42 if err := json.Unmarshal(data, &was); err != nil {
43 return fmt.Errorf("%s does not read, so whose state %s holds is not known: %v", path, dir, err)
44 }
45 if was != b {
46 return fmt.Errorf("the state directory %s belongs to %s on %s as %s, and this pass is for %s on %s as %s: give each its own --state",
47 dir, was.Target, was.Repository, was.Principal, b.Target, b.Repository, b.Principal)
48 }
49 return nil
50 case !errors.Is(err, fs.ErrNotExist):
51 return fmt.Errorf("reading what the state directory %s belongs to: %w", dir, err)
52 }
53 data, err = json.MarshalIndent(b, "", " ")
54 if err != nil {
55 return err
56 }
57 tmp, err := os.CreateTemp(dir, bindingFile+".*")
58 if err != nil {
59 return err
60 }
61 defer os.Remove(tmp.Name())
62 _, err = tmp.Write(append(data, '\n'))
63 if serr := tmp.Sync(); err == nil {
64 err = serr
65 }
66 if cerr := tmp.Close(); err == nil {
67 err = cerr
68 }
69 if err != nil {
70 return fmt.Errorf("writing what the state directory %s belongs to: %w", dir, err)
71 }
72 return os.Rename(tmp.Name(), path)
73}