gunk-dev/the-valley

state.go

sourcec3e97f086eb3main's published tip history
2.1 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, and the
21// journal (journal.go).
22const (
23 lockFile = "lock" // what a pass holds a lock on while it runs
24 bindingFile = "binding.json" // the repository, target and principal the directory belongs to
25)
26
27// binding is what a state directory belongs to: the repository as --repo
28// gave it, the target, and the principal.
29type binding struct {
30 Repository string `json:"repository"`
31 Target string `json:"target"`
32 Principal string `json:"principal"`
33}
34
35// bindState binds the state directory to b the first time a pass uses it,
36// and afterwards refuses a pass for anything else. It runs under the lock.
37func bindState(dir string, b binding) error {
38 path := filepath.Join(dir, bindingFile)
39 data, err := os.ReadFile(path)
40 switch {
41 case err == nil:
42 var was binding
43 if err := json.Unmarshal(data, &was); err != nil {
44 return fmt.Errorf("%s does not read, so whose state %s holds is not known: %v", path, dir, err)
45 }
46 if was != b {
47 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",
48 dir, was.Target, was.Repository, was.Principal, b.Target, b.Repository, b.Principal)
49 }
50 return nil
51 case !errors.Is(err, fs.ErrNotExist):
52 return fmt.Errorf("reading what the state directory %s belongs to: %w", dir, err)
53 }
54 data, err = json.MarshalIndent(b, "", " ")
55 if err != nil {
56 return err
57 }
58 if err := writeDurably(dir, bindingFile, append(data, '\n')); err != nil {
59 return fmt.Errorf("writing what the state directory %s belongs to: %w", dir, err)
60 }
61 return nil
62}