gunk-dev/the-valley

selfupdate.go

source06e50fc2f601main's published tip history
7.4 KiB
1package main
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "os/exec"
10 "os/signal"
11 "strings"
12 "syscall"
13
14 "the-valley/selfupdate"
15)
16
17const selfUpdateHelp = `usage: valley self-update [-v] [--retry | --rollback | --pin | --unpin]
18 [--repo <url>] [--branch <name>]
19
20Brings the installed valley up to the tip of a branch of the-valley, for a
21machine whose valley should follow that branch without a system rebuild.
22It is off until a repository is named, by --repo or by the user's git
23config, which is read whatever the current directory:
24
25 git config --global valley.selfUpdate.repo git@<valley host>:the-valley
26 git config --global valley.selfUpdate.branch main (the default)
27
28repo is an https://, ssh://, git:// or file:// URL, an absolute path, or
29user@host:path. user@host:path names what git itself would: a path that
30starts with / or ~ as written, and any other path under the login's home,
31read as ssh://user@host/~/path, which is how a valley host serves its
32projects. Name a forge by its https:// or ssh:// URL. Any other transport
33(ext::, fd::) and any character outside [A-Za-z0-9._~/:@-], which nix's
34flake-ref parser would re-encode, is refused. git ls-remote and nix read the
35repo by the same URL, and the git that self-update runs, directly or through
36nix, is limited to those transports (GIT_ALLOW_PROTOCOL). Each run:
37 1. takes a lock under $XDG_STATE_HOME/valley, so runs never overlap: a run
38 that finds another in progress exits 0 and says so;
39 2. resolves the branch's commit with git ls-remote;
40 3. exits 0 if the installed valley was built from that commit (quietly;
41 -v says so), or if that commit already failed to build or test (it is
42 retried when the branch moves, or with --retry);
43 4. builds exactly that commit, the flake's packages.<system>.valley:
44 nix build 'git+<repo>?ref=refs/heads/<branch>&rev=<sha>#...';
45 5. smoke-tests the build, in an environment that carries nothing of the
46 running valley's: its valley --version must report the commit, its
47 valley help must exit 0, and its valley checks --names must derive
48 the expected checks from the tiny policy the package ships, which
49 shows the schema it carries composes a policy. A failure records the
50 commit as failed, installs nothing, and exits non-zero;
51 6. installs it into the user's default nix profile in place of the
52 profile element named valley, leaving other elements alone. The system
53 valley stays underneath as the fallback;
54 7. records the current and previous store paths and commits, the time and
55 any failure in $XDG_STATE_HOME/valley/self-update.json.
56
57Only the named branch installs, pinned to the commit ls-remote returned,
58and only after it builds and passes the smoke test. Before self-update has
59installed anything, the running valley's version (valley --version) says
60which commit is installed.
61
62 -v, --verbose also say so when valley is up to date
63 --retry build the branch's tip even if it failed before
64 --rollback reinstall the previous valley; again to return to the
65 newer one
66 --pin leave the current install alone until --unpin: runs while
67 pinned exit 0 with a note, so a bad tip is not reinstalled
68 while it gets fixed
69 --unpin let self-update install the branch's tip again
70 --repo URL the repository, in place of valley.selfUpdate.repo
71 --branch NAME the branch, in place of valley.selfUpdate.branch`
72
73type selfUpdateArgs struct {
74 verbose, retry, rollback, pin, unpin bool
75 repo, branch string
76 help bool
77}
78
79func parseSelfUpdateArgs(args []string) (selfUpdateArgs, error) {
80 var a selfUpdateArgs
81 usage := "usage: valley self-update [-v] [--retry | --rollback | --pin | --unpin] [--repo <url>] [--branch <name>]"
82 for i := 0; i < len(args); i++ {
83 arg := args[i]
84 value := func(flag string) (string, error) {
85 if v, ok := strings.CutPrefix(arg, flag+"="); ok {
86 return v, nil
87 }
88 if i+1 >= len(args) {
89 return "", failure(flag + " needs a value; " + usage)
90 }
91 i++
92 return args[i], nil
93 }
94 var err error
95 switch {
96 case arg == "-v" || arg == "--verbose":
97 a.verbose = true
98 case arg == "--retry":
99 a.retry = true
100 case arg == "--rollback":
101 a.rollback = true
102 case arg == "--pin":
103 a.pin = true
104 case arg == "--unpin":
105 a.unpin = true
106 case arg == "-h" || arg == "--help":
107 a.help = true
108 case arg == "--repo" || strings.HasPrefix(arg, "--repo="):
109 a.repo, err = value("--repo")
110 case arg == "--branch" || strings.HasPrefix(arg, "--branch="):
111 a.branch, err = value("--branch")
112 default:
113 err = failure("unknown argument " + arg + "; " + usage)
114 }
115 if err != nil {
116 return a, err
117 }
118 }
119 n := 0
120 for _, set := range []bool{a.retry, a.rollback, a.pin, a.unpin} {
121 if set {
122 n++
123 }
124 }
125 if n > 1 {
126 return a, failure("--retry, --rollback, --pin and --unpin each ask for one thing; give one of them")
127 }
128 return a, nil
129}
130
131// runSelfUpdate is valley self-update (../selfupdate): it installs the tip
132// of a branch of the-valley into the user's nix profile, or rolls back,
133// pins or unpins what it installed. The running valley's version comes
134// from VALLEY_VERSION, which bin/valley passes on from its package's stamp.
135func runSelfUpdate(args []string, stdout, stderr io.Writer) int {
136 a, err := parseSelfUpdateArgs(args)
137 if err != nil {
138 fmt.Fprintf(stderr, "valley: %s\n", err)
139 return 2
140 }
141 if a.help {
142 fmt.Fprintln(stdout, selfUpdateHelp)
143 return 0
144 }
145 if err := selfUpdate(a, stdout); err != nil {
146 fmt.Fprintf(stderr, "valley: self-update: %s\n", err)
147 return 1
148 }
149 return 0
150}
151
152func selfUpdate(a selfUpdateArgs, stdout io.Writer) error {
153 dir, err := selfupdate.DefaultDir()
154 if err != nil {
155 return err
156 }
157 u := &selfupdate.Updater{Dir: dir, Version: os.Getenv("VALLEY_VERSION"), Out: stdout, Verbose: a.verbose}
158 if u.Repo = a.repo; u.Repo == "" {
159 if u.Repo, err = userConfig("valley.selfUpdate.repo"); err != nil {
160 return err
161 }
162 }
163 if u.Branch = a.branch; u.Branch == "" {
164 if u.Branch, err = userConfig("valley.selfUpdate.branch"); err != nil {
165 return err
166 }
167 }
168 if u.Branch == "" {
169 u.Branch = "main"
170 }
171
172 // A systemd stop or a ^C ends the nix build and git with it.
173 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
174 defer stop()
175 switch {
176 case a.rollback:
177 return u.Rollback(ctx)
178 case a.pin || a.unpin:
179 return u.Pin(a.pin)
180 }
181 if u.Repo == "" {
182 return failure("it is off until a repository is named, by --repo or by\n git config --global valley.selfUpdate.repo git@<valley host>:the-valley")
183 }
184 return u.Update(ctx, a.retry)
185}
186
187// userConfig reads a key of the user's own git config, "" when it is
188// unset. git runs at /, with no variable naming a repository, so no
189// repository's config is read, and the answer is the same from any
190// directory.
191func userConfig(key string) (string, error) {
192 cmd := exec.Command("git", "config", "--get", key)
193 cmd.Dir = "/"
194 for _, kv := range gitEnvironment(os.Environ()) {
195 switch name, _, _ := strings.Cut(kv, "="); name {
196 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR":
197 default:
198 cmd.Env = append(cmd.Env, kv)
199 }
200 }
201 out, err := cmd.Output()
202 var exit *exec.ExitError
203 if errors.As(err, &exit) && exit.ExitCode() == 1 {
204 return "", nil
205 }
206 if err != nil {
207 return "", fmt.Errorf("reading git config %s: %w", key, err)
208 }
209 return strings.TrimSpace(string(out)), nil
210}