-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdev
More file actions
executable file
·393 lines (353 loc) · 13.9 KB
/
Copy pathdev
File metadata and controls
executable file
·393 lines (353 loc) · 13.9 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
#!/usr/bin/env bash
# One-liner front door to the Nix dev container (hosts/container).
#
# ./dev install the WezTerm config + alias, build/start the
# container if needed, then drop into a shell inside it
# ./dev tmux same, but attach to a persistent tmux session
# ./dev rebuild rebuild the image and recreate the container
# ./dev help everything else
#
# Nix is NOT required on this machine: when the `nix` binary is missing the
# image is built inside a throwaway nixos/nix container, with the build store
# kept in a named volume so subsequent builds are incremental.
#
# Optional environment overrides:
# DEV_IMAGE image name:tag (default nix-dev:latest)
# DEV_CONTAINER container + volume prefix (default nix-dev)
# DEV_WORKPLACE host dir bind-mounted at ~/workplace (default ~/workplace)
# DEV_PLATFORM --platform for build and run (default: docker's default)
# DEV_BUILDER builder image (default nixos/nix:latest)
# DEV_DOCKER_SOCK 0 to NOT bind the host docker socket (default: bind it)
# DEV_SSH_AGENT 1 to forward the Docker Desktop ssh-agent socket
# DEV_HOST_SHARE names from PERSIST to bind from the host instead of using a
# named volume, e.g. DEV_HOST_SHARE="aws ssh codex" — auth on
# the host once and the container sees it immediately
set -euo pipefail
REPO="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
IMAGE="${DEV_IMAGE:-nix-dev:latest}"
CONTAINER="${DEV_CONTAINER:-nix-dev}"
WORKPLACE="${DEV_WORKPLACE:-$HOME/workplace}"
BUILDER="${DEV_BUILDER:-nixos/nix:latest}"
BUILD_STORE_VOLUME="${CONTAINER}-buildstore"
# `codex login` runs its OAuth callback server on 127.0.0.1:1455 inside the
# container, with the redirect_uri hardcoded to http://localhost:1455. Docker
# publishes to the container's eth0, not its loopback, so the callback cannot
# be reached directly. `./dev codex-login` runs socat on CODEX_BRIDGE_PORT
# (which docker does publish) and forwards to codex's loopback listener, so
# the browser on the host resolves localhost:1455 to the right server.
CODEX_PORT="${DEV_CODEX_PORT:-1455}"
CODEX_BRIDGE_PORT=1456
ZSHRC="${ZDOTDIR:-$HOME}/.zshrc"
ALIAS_MARKER="# nix-config dev container"
# Paths under the container's $HOME holding credentials or long-lived tool
# state. `./dev rebuild` recreates the container and discards its writable
# layer, so anything not listed here is lost. Each entry becomes a named volume
# ${CONTAINER}-<name>; adding one is a one-line change.
#
# Nothing here may collide with what the image bakes into ~ — .zshrc, .zshenv
# and .config/{btop,git,nvim,tmux} — because a volume mounted over baked
# content is seeded once and then never refreshed, leaving you on a stale copy
# after every rebuild. Only directories: docker creates a directory at the
# mount point, so a dotfile like ~/.npmrc cannot be persisted this way.
PERSIST=(
"state:.local/state" # nvim undo/shada, zsh history
"share:.local/share"
"cache:.cache"
"ssh:.ssh"
"gnupg:.gnupg"
"aws:.aws" # config, credentials, SSO cache in .aws/sso
"azure:.azure"
"gcloud:.config/gcloud"
"kube:.kube"
"k9s:.config/k9s"
"helm:.config/helm"
"docker:.docker" # registry logins
"terraform:.terraform.d"
"gh:.config/gh"
"glab:.config/glab-cli"
"copilot:.config/github-copilot"
"codex:.codex"
"maven:.m2"
)
persist_volumes() {
local entry
for entry in "${PERSIST[@]}"; do
printf '%s\n' "${CONTAINER}-${entry%%:*}"
done
}
# Names from PERSIST that should bind the host's real directory instead of
# using a named volume, so a credential you obtain on the host is immediately
# live in the container and vice versa. E.g. DEV_HOST_SHARE="aws ssh codex".
host_shared() {
local want="$1" name
# shellcheck disable=SC2086
for name in ${DEV_HOST_SHARE:-}; do
[ "$name" = "$want" ] && return 0
done
return 1
}
# Host docker socket, so the docker CLI in the container drives the host
# daemon. Docker Desktop puts it at ~/.docker/run/docker.sock and only exposes
# /var/run/docker.sock when "Allow the default Docker socket to be used" is on
# under Settings -> Advanced, so probe for whichever exists.
host_docker_sock() {
local candidate
for candidate in "${DEV_DOCKER_SOCK_PATH:-}" /var/run/docker.sock \
"$HOME/.docker/run/docker.sock"; do
if [ -n "$candidate" ] && [ -S "$candidate" ]; then
printf '%s' "$candidate"
return 0
fi
done
return 1
}
say() { printf '\033[1;32m==>\033[0m %s\n' "$*" >&2; }
warn() { printf '\033[1;33m==>\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m==>\033[0m %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }
platform_args() {
[ -n "${DEV_PLATFORM:-}" ] && printf '%s\n%s\n' --platform "$DEV_PLATFORM"
}
require_docker() {
have docker || die "docker not found on PATH"
docker info >/dev/null 2>&1 || die "docker is installed but not running"
}
# --- image ------------------------------------------------------------------
image_exists() { docker image inspect "$IMAGE" >/dev/null 2>&1; }
build_image() {
# The flake exposes the linux systems only; ask for the one matching the
# image we are about to run rather than the host's own system.
local system attr
case "${DEV_PLATFORM:-$(docker version --format '{{.Server.Os}}/{{.Server.Arch}}')}" in
*/arm64 | */aarch64) system=aarch64-linux ;;
*) system=x86_64-linux ;;
esac
attr="packages.${system}.devcontainer-stream"
# `path:` rather than a bare path so the build sees the working tree as-is,
# instead of git-flake semantics where uncommitted files are invisible.
if have nix; then
say "Building $IMAGE with the local nix ($system)"
local streamer
streamer="$(nix build --no-link --print-out-paths "path:${REPO}#${attr}")"
"$streamer" | docker load
else
say "No local nix; building $IMAGE inside $BUILDER ($system)"
# Nix's own logs go to stderr, so stdout is just the image tarball.
# shellcheck disable=SC2046
docker run --rm -i \
$(platform_args) \
-v "${REPO}:/repo:ro" \
-v "${BUILD_STORE_VOLUME}:/nix" \
"$BUILDER" \
sh -c 'exec $(nix --extra-experimental-features "nix-command flakes" \
build --no-link --print-out-paths "path:/repo#'"${attr}"'")' \
| docker load
fi
}
ensure_image() {
if image_exists; then
return
fi
build_image
}
# --- container --------------------------------------------------------------
# `docker container inspect` writes a stray empty line to stdout when the
# container does not exist, so key off the exit status rather than the output,
# and scope to containers so an image of the same name cannot match.
container_state() {
local out
if out="$(docker container inspect -f '{{.State.Status}}' "$CONTAINER" 2>/dev/null)"; then
printf '%s' "$out" | tr -d '[:space:]'
else
printf 'missing'
fi
}
create_container() {
[ -d "$WORKPLACE" ] || { say "Creating $WORKPLACE"; mkdir -p "$WORKPLACE"; }
local args=(
--name "$CONTAINER"
--hostname "$CONTAINER"
--detach --interactive --tty
# host.docker.internal is built in on Docker Desktop; this makes it resolve
# on plain Linux docker too, so avante can reach ollama on the host.
--add-host "host.docker.internal:host-gateway"
# Host-loopback only: this is an OAuth callback, nothing that should be
# reachable from the network.
-p "127.0.0.1:${CODEX_PORT}:${CODEX_BRIDGE_PORT}"
-v "${WORKPLACE}:/root/workplace"
)
# Credentials and tool state that must outlive `./dev rebuild`; everything
# else is baked into the image and comes back on rebuild.
local entry name path
for entry in "${PERSIST[@]}"; do
name="${entry%%:*}"
path="${entry#*:}"
if host_shared "$name"; then
if [ -e "$HOME/$path" ]; then
args+=(-v "$HOME/${path}:/root/${path}")
continue
fi
warn "DEV_HOST_SHARE lists '$name' but $HOME/$path is missing; using a volume"
fi
args+=(-v "${CONTAINER}-${name}:/root/${path}")
done
[ -n "${DEV_PLATFORM:-}" ] && args+=(--platform "$DEV_PLATFORM")
[ "${DEV_SSH_AGENT:-0}" = 1 ] &&
args+=(-v /run/host-services/ssh-auth.sock:/ssh-agent -e SSH_AUTH_SOCK=/ssh-agent)
if [ "${DEV_DOCKER_SOCK:-1}" = 1 ]; then
local sock
if sock="$(host_docker_sock)"; then
args+=(-v "${sock}:/var/run/docker.sock")
else
warn "No host docker socket found; docker inside the container will not work."
warn "Enable Settings -> Advanced -> 'Allow the default Docker socket to be used',"
warn "or point DEV_DOCKER_SOCK_PATH at it."
fi
fi
say "Creating $CONTAINER from $IMAGE (${WORKPLACE} -> /root/workplace)"
docker run "${args[@]}" "$IMAGE" >/dev/null
}
ensure_container() {
ensure_image
case "$(container_state)" in
running) ;;
missing) create_container ;;
*) say "Starting $CONTAINER"; docker start "$CONTAINER" >/dev/null ;;
esac
}
# --- host-side setup --------------------------------------------------------
install_wezterm_config() {
local force="${1:-}" dest="$HOME/.config/wezterm"
if [ -e "$dest/wezterm.lua" ] && [ "$force" != "--force" ]; then
return
fi
say "Installing WezTerm config into $dest"
mkdir -p "$dest/colors"
cp "$REPO/dotfiles/wezterm/wezterm.lua" "$dest/wezterm.lua"
cp "$REPO"/dotfiles/wezterm/colors/*.toml "$dest/colors/"
warn "WezTerm needs JetBrains Mono: brew install --cask font-jetbrains-mono"
}
install_alias() {
# On a Home Manager machine ~/.zshrc is a read-only store symlink; appending
# would fail, and the alias belongs in the nix config there anyway.
if [ -L "$ZSHRC" ] && case "$(readlink "$ZSHRC")" in /nix/store/*) true ;; *) false ;; esac; then
warn "$ZSHRC is managed by Nix; add the alias there instead:"
warn " alias dev=$REPO/dev"
return
fi
[ -e "$ZSHRC" ] || touch "$ZSHRC"
if grep -qF "$ALIAS_MARKER" "$ZSHRC"; then
return
fi
say "Adding 'dev' alias to $ZSHRC"
printf '\n%s\nalias dev=%q\n' "$ALIAS_MARKER" "$REPO/dev" >>"$ZSHRC"
warn "Run 'source $ZSHRC' (or open a new tab) to pick up the alias"
}
# --- commands ---------------------------------------------------------------
# -t only when there is a terminal to attach to, so `./dev exec ...` still works
# from a script or a pipeline.
docker_exec() {
# HOST_TERM rather than TERM: the container's .zshenv adopts it only if the
# image has a matching terminfo entry, so an exotic host TERM cannot leave
# tmux and nvim with a terminal they cannot drive.
local flags=(-i -e "HOST_TERM=${TERM:-}")
if [ -t 0 ] && [ -t 1 ]; then
flags+=(-t)
fi
exec docker exec "${flags[@]}" "$CONTAINER" "$@"
}
cmd_shell() { ensure_container; docker_exec /bin/zsh -l; }
cmd_tmux() {
ensure_container
docker_exec /bin/zsh -lc 'tmux new -A -s main'
}
cmd_attach() {
ensure_container
warn "Detach with ctrl-p ctrl-q; ctrl-d would stop the container"
exec docker attach "$CONTAINER"
}
cmd_exec() { ensure_container; docker_exec "$@"; }
cmd_codex_login() {
ensure_container
if ! docker port "$CONTAINER" "$CODEX_BRIDGE_PORT" >/dev/null 2>&1; then
die "$CONTAINER has no published callback port; run './dev rm' then './dev'"
fi
local flags=(-i)
if [ -t 0 ] && [ -t 1 ]; then
flags+=(-t)
fi
say "Bridging host 127.0.0.1:${CODEX_PORT} -> container 127.0.0.1:1455"
docker exec -d "$CONTAINER" /bin/sh -c \
"socat TCP-LISTEN:${CODEX_BRIDGE_PORT},fork,reuseaddr TCP:127.0.0.1:1455" \
>/dev/null
warn "Open the printed URL in your browser; the localhost:${CODEX_PORT} redirect will reach the container."
docker exec "${flags[@]}" "$CONTAINER" /bin/zsh -lc 'codex login' || true
docker exec "$CONTAINER" \
pkill -f "TCP-LISTEN:${CODEX_BRIDGE_PORT}" >/dev/null 2>&1 || true
}
cmd_rebuild() {
build_image
if [ "$(container_state)" != missing ]; then
say "Recreating $CONTAINER"
docker rm -f "$CONTAINER" >/dev/null
fi
create_container
}
cmd_status() {
printf 'repo: %s\n' "$REPO"
printf 'image: %s (%s)\n' "$IMAGE" \
"$(image_exists && echo present || echo missing)"
printf 'container: %s (%s)\n' "$CONTAINER" "$(container_state)"
printf 'workplace: %s -> /root/workplace\n' "$WORKPLACE"
}
cmd_help() {
awk 'NR>1 && /^#/ { sub(/^# ?/, ""); print; next } NR>1 { exit }' \
"${BASH_SOURCE[0]}"
cat <<'EOF'
Commands:
(none) setup + shell shell zsh inside the container
tmux attach tmux session attach docker attach to PID 1
exec ARGS run a command inside status show what exists
build build the image rebuild rebuild image + container
start/stop/restart rm remove container + volumes
wezterm [--force] install the WezTerm config
alias add the 'dev' alias to ~/.zshrc
codex-login run `codex login` with its OAuth callback bridged to the host
EOF
}
main() {
local cmd="${1:-default}"
[ $# -gt 0 ] && shift
case "$cmd" in
default)
require_docker
install_wezterm_config
install_alias
cmd_shell
;;
shell) require_docker; cmd_shell ;;
tmux) require_docker; cmd_tmux ;;
attach) require_docker; cmd_attach ;;
exec) require_docker; cmd_exec "$@" ;;
codex-login) require_docker; cmd_codex_login ;;
build) require_docker; build_image ;;
rebuild) require_docker; cmd_rebuild ;;
up) require_docker; ensure_container; cmd_status ;;
start) require_docker; docker start "$CONTAINER" ;;
stop) require_docker; docker stop "$CONTAINER" ;;
restart) require_docker; docker restart "$CONTAINER" ;;
rm)
require_docker
docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
# shellcheck disable=SC2046
docker volume rm $(persist_volumes) >/dev/null 2>&1 || true
say "Removed $CONTAINER and its state volumes"
;;
status) require_docker; cmd_status ;;
wezterm) install_wezterm_config "${1:-}" ;;
alias) install_alias ;;
help | -h | --help) cmd_help ;;
*) die "unknown command '$cmd' (try ./dev help)" ;;
esac
}
main "$@"