Repository navigation
Expand file tree
/
Copy pathflake.nix
More file actions
602 lines (564 loc) · 28.2 KB
/
Copy pathflake.nix
File metadata and controls
602 lines (564 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
{
description = "figaro";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
# figwal is IN THIS TREE, at internal/store/{segment,disk,log,xwal},
# so it is neither a module requirement nor a flake input and no
# version, pseudo-version or vendorHash bookkeeping attends a change
# to it. The vendorHash below still covers the remaining external
# dependencies; reset it from the "got:" value nix prints when one of
# THOSE moves.
};
outputs = { self, nixpkgs }:
let
supportedSystems = [
"x86_64-linux"
"aarch64-linux"
"aarch64-darwin"
"x86_64-darwin"
];
forAllSystems = f: nixpkgs.lib.genAttrs supportedSystems (system: f {
pkgs = nixpkgs.legacyPackages.${system};
});
in
{
# benchstat is NOT in nixpkgs, so it is built here rather than assumed
# to be on somebody's PATH. It parses the documented Go benchmark
# format; hand-rolled positional parsing of that output is what
# produced this campaign's worst instrument failure.
overlays.default = final: prev: {
figaro = final.buildGoModule rec {
pname = "figaro";
version = "0.38.2";
src = self;
vendorHash = "sha256-sTOoAKFZmXAoZlTIOyUpoyZIRjxS697JhlbjU+ctflo=";
subPackages = [ "cmd/figaro" ];
env.CGO_ENABLED = 0;
nativeBuildInputs = [ final.installShellFiles ];
# self.shortRev is a clean 7-char hash; dirtyShortRev appends
# "-dirty". Strip the suffix so cli.commit gets the bare rev
# and cli.commitDirty carries the dirty signal separately.
rev =
if self ? rev then builtins.substring 0 12 self.rev
else if self ? dirtyRev then builtins.substring 0 12 self.dirtyRev
else "unknown";
dirty = if self ? dirtyRev then "true" else "";
ldflags = [
"-s" "-w"
# The single live version: this string is what `figaro --version`
# reports, and the release script mints the matching vX.Y.Z tag
# from the same line above. Nothing else declares a version.
"-X github.com/jack-work/figaro/internal/cli.semver=${version}"
"-X github.com/jack-work/figaro/internal/cli.commit=${rev}"
"-X github.com/jack-work/figaro/internal/cli.commitDirty=${dirty}"
];
# Multi-call shims used to live here (q/l/x symlinks); they
# were moved to user shell aliases. See ~/.config/fish/config.fish.
#
# `fig` is different: it's a pure rename (no argv rewrite),
# so we install it as a symlink next to figaro. main.go uses
# filepath.Base(os.Args[0]) so help/usage/completion reflect
# whichever name was invoked. Users installing via `go install`
# can replicate this with: ln -s figaro $(go env GOPATH)/bin/fig
#
# Shell completions are generated from the freshly-built
# binary and dropped into the standard nixpkgs autoload
# paths ($out/share/{bash-completion,zsh/site-functions,
# fish/vendor_completions.d}). Every nix rebuild produces a
# matching script atomically with the binary: no more stale
# on-disk completions after an upgrade. The canExecute guard
# skips generation when cross-compiling (host can't run the
# just-built binary); installShellCompletion is still safe to
# call from cross builds, the scripts just won't be present.
# The first-party skill no longer travels beside the binary: it
# travels INSIDE it. skills.go embeds skills/figaro, and
# internal/outfit unpacks it to a content-hashed directory under
# the state dir on first use. That is what makes a one line install
# possible (one file to download), and it moves the old "refusing
# to ship a binary with no first-party skills" check from this
# postInstall to the compiler: delete skills/figaro and the embed
# directive fails the build.
postInstall = ''
ln -s figaro $out/bin/fig
'' + final.lib.optionalString
(final.stdenv.buildPlatform.canExecute final.stdenv.hostPlatform) ''
installShellCompletion --cmd figaro \
--bash <($out/bin/figaro completion bash) \
--zsh <($out/bin/figaro completion zsh) \
--fish <($out/bin/figaro completion fish)
installShellCompletion --cmd fig \
--bash <($out/bin/fig completion bash) \
--zsh <($out/bin/fig completion zsh) \
--fish <($out/bin/fig completion fish)
'';
meta.mainProgram = "figaro";
};
};
packages = forAllSystems ({ pkgs }: rec {
figaro = (import nixpkgs {
inherit (pkgs) system;
overlays = [ self.overlays.default ];
}).figaro;
default = figaro;
});
devShells = forAllSystems ({ pkgs }: let
figaroPkg = self.packages.${pkgs.system}.default;
# benchstat is NOT in nixpkgs, so it is BUILT here rather than
# assumed to be on somebody's PATH. It parses the DOCUMENTED Go
# benchmark format, with named units; hand-rolled positional parsing
# of that output produced this campaign's worst instrument failure --
# b.ReportMetric shifts every column after it, so awk reading "field
# 5" silently compared a hardcoded metric value against itself across
# a sabotage and reported a clean result. A wrong number survives
# every check a missing number fails.
benchstatPkg = pkgs.buildGoModule {
pname = "benchstat";
version = "0.0-x-perf";
src = pkgs.fetchFromGitHub {
owner = "golang";
repo = "perf";
rev = "fd4a688df89207abdabe0a0cf5b2cd9ccfd376d2";
hash = "sha256-YgMIIF9DAjyAPpZJtVoOKSatNhRPg/nPOYr0P06Fi5s=";
};
vendorHash = "sha256-AZx9tPzsPvjc5kpmiBa6eYKtrw0hczYi0sbcd/lkiiA=";
subPackages = [ "cmd/benchstat" ];
};
# Each override knob is an attribute on a profile. A null
# value means "inherit from the real user environment": the
# corresponding env var is left untouched. A string means
# "set this env var"; "@dev" is a sentinel expanded to a
# dev-scoped path under $FIGARO_DEV_ROOT/<knob>.
#
# The dev-shell knobs are:
#
# runtime → FIGARO_RUNTIME_DIR (socket, bindings, PID)
# config → FIGARO_CONFIG_DIR (outfits, providers, config.toml)
# state → FIGARO_STATE_DIR (arias, OTel data)
# hush → FIGARO_HUSH_APP (hush identity + socket)
#
# All four default to "@dev" in the helper, so the helper
# caller only overrides what they want to share. The named
# presets at the bottom show common compositions.
#
# Note: hush's @dev sentinel resolves to a string AppName
# like "figaro-dev-<profile>", not a path, because hush
# derives its own dirs from AppName internally. To share the
# global hush identity, set hush = null.
# seedConfig copies the real config into a dev-scoped config dir on
# first entry, so a shell can be given your actual outfits, skills and
# credo while every write lands on the copy. Credentials are NOT
# copied: providers/ is symlinked, so a secret is never duplicated on
# disk, and hush is left to its own knob.
mkFigaroShell = {
name,
runtime ? "@dev",
config ? "@dev",
state ? "@dev",
hush ? "@dev",
seedConfig ? false,
}: let
# Translate a knob value into a shell snippet that either
# exports the env var or leaves it inherited. "@dev" is
# expanded to a path under $FIGARO_DEV_ROOT.
#
# All branches use `: "''${VAR:=...}"` instead of `export
# VAR=...` so a pre-set env var from the caller's shell
# wins. This makes the presets composable from outside:
# `FIGARO_HUSH_APP=figaro nix develop .#clean` will keep
# the caller's value rather than overwriting it.
mkKnob = envVar: subdir: value:
if value == null then ''
# ${envVar}: inheriting real user environment
''
else if value == "@dev" then ''
: "''${${envVar}:=$FIGARO_DEV_ROOT/${subdir}}"
export ${envVar}
mkdir -p "''${${envVar}}"
''
else ''
: "''${${envVar}:=${value}}"
export ${envVar}
'';
mkHushKnob = value:
if value == null then ''
# FIGARO_HUSH_APP: inheriting (uses real "figaro" identity)
#
# figaro's managed hush derives its agent-socket dir from
# os.TempDir()/<app>-hush: NOT XDG_RUNTIME_DIR, and with no env
# override in the shared (nil-Dirs) path. Nix rewrites TMPDIR to a
# per-shell dir ($TMPDIR=/tmp/nix-shell.XXX), so inside the shell
# figaro would look for the agent at
# /tmp/nix-shell.XXX/figaro-hush/agent.sock while the real global
# agent (started with the ambient TMPDIR) listens at
# /tmp/figaro-hush/agent.sock → "connection refused", no shared
# credential. Reset the nix override back to the ambient default so
# a shared-hush shell actually reaches the running global agent.
case "''${TMPDIR:-}" in
/tmp/nix-shell.*|"") export TMPDIR=/tmp ;;
esac
''
else if value == "@dev" then ''
: "''${FIGARO_HUSH_APP:=figaro-dev-${name}}"
export FIGARO_HUSH_APP
# Isolated, EMBEDDED hush rooted under the dev root: its own
# identity + encrypted secrets + agent socket (<dir>/run),
# re-authenticated per shell. Stable per shell (not the
# nix-shell $TMPDIR), so figaro runs its own hush instance
# instead of reaching the user's shared agent (whose socket
# isn't reachable from inside the sandbox).
: "''${FIGARO_HUSH_DIR:=$FIGARO_DEV_ROOT/hush}"
export FIGARO_HUSH_DIR
mkdir -p "''${FIGARO_HUSH_DIR}"
# Test-only autogenerated passphrase: unlocks this isolated dev
# hush without an interactive prompt, so a detached daemon (e.g.
# the one `figaro ls` spawns) doesn't hang on first run. figaro
# honors FIGARO_HUSH_PASSPHRASE only when FIGARO_HUSH_DIR is set,
# so it can never touch the real keystore. Stable per dev root
# (the identity it creates must be unlockable on re-entry);
# removed when you tear the dev root down (rm -rf $FIGARO_DEV_ROOT).
if [ ! -f "$FIGARO_DEV_ROOT/hush-passphrase" ]; then
( umask 077; head -c 24 /dev/urandom | base64 | tr -d '\n' > "$FIGARO_DEV_ROOT/hush-passphrase" )
fi
export FIGARO_HUSH_PASSPHRASE="$(cat "$FIGARO_DEV_ROOT/hush-passphrase")"
# NOTE: the embedded managed hush unlocks via the OS keyring: it
# persists the passphrase on first-run and reads it back on every
# later unlock/agent-respawn. So we do NOT clear the keyring on
# entry (that would break non-interactive unlock of the existing
# identity). It's a dev-scoped entry (service = $FIGARO_HUSH_APP)
# keyed to the stable per-dev-root passphrase, so it stays
# consistent across sessions. Full teardown, if you want the test
# credential gone from the keyring too:
# rm -rf $FIGARO_DEV_ROOT
# secret-tool clear service $FIGARO_HUSH_APP username default
''
else ''
: "''${FIGARO_HUSH_APP:=${value}}"
export FIGARO_HUSH_APP
'';
in pkgs.mkShell {
inherit name;
buildInputs = with pkgs; [
go gopls gotools
# tmux, because the ONLY honest test of anything that paints is a
# real binary in a real pty. The smoke suite skips silently when
# tmux is absent (a test that quietly does not run is worse than
# one that fails), and a dev shell that does not carry it makes
# that skip the default -- so the suite would be green, unrun, and
# indistinguishable from green and run.
tmux
# benchstat parses the DOCUMENTED Go benchmark format (named
# units), which a positional parser does not. b.ReportMetric
# shifts every column after it, so awk reading "field 5" silently
# read a hardcoded metric value as B/op and compared it against
# itself across a sabotage -- a stable, reproducible, plausible
# WRONG NUMBER. Never hand-roll this parse.
benchstatPkg
] ++ [ figaroPkg ];
shellHook = ''
: "''${FIGARO_DEV_ROOT:=''${XDG_RUNTIME_DIR:-/tmp}/figaro-dev-${name}}"
export FIGARO_DEV_ROOT
mkdir -p "$FIGARO_DEV_ROOT"
chmod 700 "$FIGARO_DEV_ROOT"
${mkKnob "FIGARO_RUNTIME_DIR" "run" runtime}
${mkKnob "FIGARO_CONFIG_DIR" "config" config}
${mkKnob "FIGARO_STATE_DIR" "state" state}
${mkHushKnob hush}
${if seedConfig then ''
# Seed the dev config dir with a COPY of the real one, once per dev
# root. Everything that DEFINES a composition travels: config.toml,
# outfits (or a pre-rename loadouts/), skills, credo: so the shell
# sees your real outfits and can be edited freely without touching
# them.
#
# providers/ is SYMLINKED rather than copied: it holds credentials,
# and one copy of a secret on disk is enough. hush follows its own
# knob, so pass hush = null to reach the real agent.
figaro-config-reseed() {
local src="''${XDG_CONFIG_HOME:-$HOME/.config}/figaro"
if [ ! -d "$src" ]; then
echo "sandbox: no config at $src" >&2; return 1
fi
mkdir -p "$FIGARO_CONFIG_DIR"
local entry base
for entry in "$src"/*; do
[ -e "$entry" ] || continue
base="$(basename "$entry")"
case "$base" in
providers|hush|hush.bak-*) continue ;;
esac
rm -rf "$FIGARO_CONFIG_DIR/$base"
cp -a "$entry" "$FIGARO_CONFIG_DIR/$base"
done
if [ -d "$src/providers" ]; then
ln -sfn "$src/providers" "$FIGARO_CONFIG_DIR/providers"
fi
date -Is > "$FIGARO_CONFIG_DIR/.config-copied"
echo "sandbox: config copied from $src (providers symlinked)" >&2
}
if [ ! -e "$FIGARO_CONFIG_DIR/.config-copied" ]; then
figaro-config-reseed
else
echo "sandbox: reusing config copy from $(cat "$FIGARO_CONFIG_DIR/.config-copied")" >&2
echo "sandbox: figaro-config-reseed for a fresh one; rm -rf \$FIGARO_DEV_ROOT to discard" >&2
fi
'' else ""}
${if name == "snapshot" then ''
# Seed the dev state dir with a COPY of the real arias, once per
# dev root. The source is only ever read; every write in this shell
# lands on the copy. Nothing here can reach the live daemon, whose
# runtime dir is dev-scoped above.
figaro-snapshot-reseed() {
local src="''${XDG_STATE_HOME:-$HOME/.local/state}/figaro/arias"
if [ ! -d "$src" ]; then
echo "snapshot: no arias at $src" >&2; return 1
fi
echo "snapshot: copying $(du -sh "$src" | cut -f1) from $src ..." >&2
rm -rf "$FIGARO_STATE_DIR/arias"
mkdir -p "$FIGARO_STATE_DIR"
cp -a "$src" "$FIGARO_STATE_DIR/arias"
date -Is > "$FIGARO_STATE_DIR/.snapshot-taken"
echo "snapshot: ready at $FIGARO_STATE_DIR/arias" >&2
}
if [ ! -e "$FIGARO_STATE_DIR/.snapshot-taken" ]; then
figaro-snapshot-reseed
else
echo "snapshot: reusing copy from $(cat "$FIGARO_STATE_DIR/.snapshot-taken")" >&2
echo "snapshot: figaro-snapshot-reseed for a fresh one; rm -rf \$FIGARO_DEV_ROOT to discard" >&2
fi
'' else ""}
# Point figaro/fig/q at THIS worktree's build, in a bin dir
# prepended to PATH. We symlink all three names (not just q) so a
# global figaro install can't shadow the dev binary. NOTE: an
# interactive shell launched inside the dev shell (e.g. fish) may
# re-prepend its own ~/go/bin or ~/.nix-profile to PATH and shadow
# this again: guard it by re-prepending $FIGARO_DEV_BIN at the end
# of your shell rc when it is set (see ~/.config/fish/config.fish).
export FIGARO_DEV_BIN="$FIGARO_DEV_ROOT/bin"
mkdir -p "$FIGARO_DEV_BIN"
for n in figaro fig q; do
ln -sf "${figaroPkg}/bin/figaro" "$FIGARO_DEV_BIN/$n"
done
export PATH="$FIGARO_DEV_BIN:$PATH"
echo "[figaro-dev:${name}] figaro = $(command -v figaro)" >&2
for v in FIGARO_RUNTIME_DIR FIGARO_CONFIG_DIR FIGARO_STATE_DIR FIGARO_HUSH_APP; do
if [ -n "''${!v:-}" ]; then
printf "[figaro-dev:${name}] %-20s = %s\n" "$v" "''${!v}" >&2
else
printf "[figaro-dev:${name}] %-20s = (inherited)\n" "$v" >&2
fi
done
'';
};
in {
# The default shell: fully inherited environment. Use this
# to develop against the real daemon/config/state/hush. The
# in-shell binary is still the worktree build (via
# buildInputs), so you're testing your changes against your
# real data. Equivalent to the old default.
default = mkFigaroShell {
name = "default";
runtime = null;
config = null;
state = null;
hush = null;
};
# Fully hermetic: every singleton path is dev-scoped.
# First invocation will trigger the hush + figaro first-run
# flow. Use this for testing first-run UX or for completely
# blank-slate experiments.
clean = mkFigaroShell { name = "clean"; };
# Share the global hush identity (so you don't have to
# re-add provider keys) but isolate runtime/config/state.
# Useful for testing new outfits/configs against real
# provider credentials without polluting the real config.
share-hush = mkFigaroShell {
name = "share-hush";
hush = null;
};
# Share config (real providers, real outfits) but isolate
# runtime + state AND run an isolated, embedded hush (its own
# identity, re-authenticated per shell: `q login` or set
# ANTHROPIC_API_KEY on first use). The shared agent's socket
# isn't reachable from inside the sandbox, so this gives a
# self-contained hush instead. NOTE: AGE-ENC provider keys in
# the shared config can't be decrypted by the fresh identity -
# re-auth the provider (OAuth/login or a plaintext/env key).
share-config = mkFigaroShell {
name = "share-config";
config = null;
hush = "@dev";
};
# A COPY of your real arias + config, isolated in a dev root.
#
# For migrations and anything else that rewrites the store on disk,
# where the only honest fixture is your actual data and the only safe
# one is a copy of it. Runtime/state/hush are dev-scoped, so the live
# daemon is never touched; the snapshot is seeded once per dev root and
# then belongs to you.
#
# It is DISPOSABLE by design and it is not cheap (the author's store is
# ~385MB). Tear it down when the experiment is over:
# rm -rf $FIGARO_DEV_ROOT
#
# Re-seed a fresh copy without leaving the shell:
# figaro-snapshot-reseed
snapshot = mkFigaroShell {
name = "snapshot";
config = null; # read the real outfits/providers; never written
hush = null; # real credentials, so a migrated aria can be run
};
# A COPY of your real config, isolated in a dev root.
#
# `nix develop .#sandbox` gives you your actual outfits, skills and
# credo: writable, and reachable by `figaro outfit --tree`: with the
# runtime and state dev-scoped so the live daemon and your arias are
# never touched. hush is shared, so turns can actually run.
#
# Credentials are not duplicated: providers/ is a symlink to the real
# one. Everything else is a copy and belongs to you.
#
# Re-seed without leaving the shell: figaro-config-reseed
# Discard it entirely: rm -rf $FIGARO_DEV_ROOT
sandbox = mkFigaroShell {
name = "sandbox";
seedConfig = true;
hush = null; # real credentials, so the copy can run a turn
};
# `nix develop .#tools` is the shell for changing what figaro
# DEPENDS ON. Every other shell has the built figaro on PATH, which
# means entering one builds the package -- and a package build fails
# the moment go.mod moves ahead of vendorHash. That is a deadlock:
# you cannot run `go get` in a shell that will not open until after
# the `go get`. This shell holds the toolchain and nothing else, so
# the order is: enter it, bump, read nix's "got:" hash, reset
# vendorHash, and go back to a real shell.
tools = pkgs.mkShell {
name = "figaro-tools";
buildInputs = with pkgs; [ go gopls gotools git ] ++ [ benchstatPkg ];
shellHook = "echo '[figaro-dev:tools] toolchain only (no figaro build); for go get / go mod tidy / vendorHash bumps'";
};
# `nix develop .#swap` enters a shell that swaps the user's
# installed figaro for this worktree's build. The previous
# profile entry is captured on entry and restored on exit, so
# the shell behaves like a temporary "try this version" gate.
#
# On entry:
# 1. Stop the running daemon with --keep-pids so PID
# bindings get persisted to disk and any next `fig`
# invocation can restore them.
# 2. Find the current figaro entry in the user's nix
# profile (by storePath match against "figaro-VERSION").
# Capture its key and originalUrl.
# 3. Remove the captured entry.
# 4. Install this worktree's freshly-built figaro by store
# path.
#
# On exit (bash EXIT trap):
# 1. Stop the worktree daemon with --keep-pids (bindings
# survive the swap-back).
# 2. Remove the worktree entry from the profile.
# 3. Reinstall the captured original entry, preferring its
# originalUrl so the user's flake-tracking is preserved
# (e.g. `git+file:...?ref=main`). Fall back to the store
# path if no URL was captured.
#
# The store path of the worktree build is passed in via the
# FIGARO_WORKTREE_PATH env var so Nix builds the package
# before the shellHook runs (the path interpolation forces
# evaluation). It's also added to buildInputs so the binary
# is on the in-shell PATH directly, independent of profile
# state: defensive against a partial enter-failure.
#
# Edge cases:
# - No existing figaro in profile: skip save/restore; just
# install + remove the worktree entry.
# - jq absent: nothing parses; abort early.
# - SIGKILL of the shell: the EXIT trap doesn't fire,
# profile stays on the worktree entry. Recover with a
# fresh `nix develop .#swap` + exit.
swap = pkgs.mkShell {
name = "figaro-swap";
buildInputs = with pkgs; [
go gopls gotools
jq # JSON parse of `nix profile list --json`
nix # explicit so the version in the shell matches
] ++ [ self.packages.${pkgs.system}.default ];
FIGARO_WORKTREE_PATH = "${self.packages.${pkgs.system}.default}";
shellHook = ''
set -u
_figaro_swap_find_entry() {
nix profile list --json 2>/dev/null | jq -r '
.elements | to_entries[]
| select(.value.storePaths[]? | test("/[a-z0-9]+-figaro-[0-9]+(\\.[0-9]+)*$"))
| .key
' | head -1
}
_figaro_swap_stop_daemon() {
# Use whichever `fig` is on PATH at the moment; bindings
# get written to disk regardless of which version it is.
if command -v fig >/dev/null 2>&1; then
fig stop --keep-pids >/dev/null 2>&1 || true
fi
}
_figaro_swap_enter() {
if ! command -v jq >/dev/null 2>&1; then
echo "[figaro-swap] jq missing; aborting" >&2
return 1
fi
local entry old_path old_url
entry=$(_figaro_swap_find_entry || true)
if [ -n "$entry" ]; then
old_path=$(nix profile list --json \
| jq -r --arg k "$entry" '.elements[$k].storePaths[0]')
old_url=$(nix profile list --json \
| jq -r --arg k "$entry" '.elements[$k].originalUrl // empty')
export FIGARO_SWAP_OLD_KEY="$entry"
export FIGARO_SWAP_OLD_PATH="$old_path"
export FIGARO_SWAP_OLD_URL="$old_url"
echo "[figaro-swap] saving profile entry:" >&2
echo " key: $entry" >&2
echo " path: $old_path" >&2
[ -n "$old_url" ] && echo " url: $old_url" >&2
else
echo "[figaro-swap] no figaro in profile; nothing to restore on exit" >&2
fi
_figaro_swap_stop_daemon
if [ -n "''${FIGARO_SWAP_OLD_KEY:-}" ]; then
nix profile remove "$FIGARO_SWAP_OLD_KEY" >&2
fi
nix profile install "$FIGARO_WORKTREE_PATH"
echo "[figaro-swap] worktree figaro installed: $FIGARO_WORKTREE_PATH" >&2
}
_figaro_swap_exit() {
echo "[figaro-swap] exit: restoring previous figaro" >&2
_figaro_swap_stop_daemon
# The worktree entry will be keyed by its derivation name
# since we installed it by store path. Re-find it now in
# case other profile churn happened.
local current
current=$(nix profile list --json 2>/dev/null \
| jq -r --arg p "$FIGARO_WORKTREE_PATH" '
.elements | to_entries[]
| select(.value.storePaths[]? == $p)
| .key' | head -1)
if [ -n "$current" ]; then
nix profile remove "$current" >&2 || true
fi
if [ -n "''${FIGARO_SWAP_OLD_URL:-}" ]; then
nix profile install "$FIGARO_SWAP_OLD_URL" >&2
echo "[figaro-swap] restored via flake url: $FIGARO_SWAP_OLD_URL" >&2
elif [ -n "''${FIGARO_SWAP_OLD_PATH:-}" ]; then
nix profile install "$FIGARO_SWAP_OLD_PATH" >&2
echo "[figaro-swap] restored via store path: $FIGARO_SWAP_OLD_PATH" >&2
else
echo "[figaro-swap] nothing captured to restore" >&2
fi
}
_figaro_swap_enter
trap _figaro_swap_exit EXIT
echo "[figaro-swap] active: exit shell to restore the previous figaro" >&2
'';
};
});
};
}