From 04400f44d2270940b34167d8492f733b4e153258 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 16:46:19 +0100 Subject: [PATCH 01/32] add Homebrew tap formula --- Formula/devtools.rb | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Formula/devtools.rb diff --git a/Formula/devtools.rb b/Formula/devtools.rb new file mode 100644 index 0000000..38d1487 --- /dev/null +++ b/Formula/devtools.rb @@ -0,0 +1,27 @@ +class Devtools < Formula + desc "Development tools for The Developer Society" + homepage "https://github.com/developersociety/tools" + + # The tap and the tools share one repo, so a pinned revision would need a second commit after + # every tag. Instead the version is what Homebrew keys its cache on: bump it to ship a release, + # and Homebrew refetches master. + url "git@github.com:developersociety/tools.git", using: :git, branch: "master" + version "1.0.0" + + depends_on "aws-vault" + depends_on "awscli" + depends_on "gh" + depends_on "jq" + depends_on "opentofu" + + # The 1Password CLI is a cask, which formulae can't depend on, and pyenv/virtualenvwrapper are + # only needed by "dev clone". The scripts which need them say so when they're missing. + + def install + bin.install Dir["bin/dev*"] + end + + test do + assert_match "Usage: dev ", shell_output("#{bin}/dev help") + end +end From 3f7d9f01c73e66c868c7c151526bff9012dcabe1 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:52 +0100 Subject: [PATCH 02/32] add dev dispatcher which finds and documents its subcommands --- bin/dev | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100755 bin/dev diff --git a/bin/dev b/bin/dev new file mode 100755 index 0000000..ea6121a --- /dev/null +++ b/bin/dev @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# Homebrew symlinks every dev-* script into the same bin directory as this one, so siblings can +# always be found relative to $0 without resolving symlinks. +BINDIR="$(cd "$(dirname "$0")" && pwd)" + +# Each script documents itself in the comment block starting at its "# help:" line, so there is +# no separate list of usage text to keep in step with the scripts. +doc_block() { + awk ' + /^# help: / { inblock = 1 } + inblock && !/^#/ { exit } + inblock { sub(/^# ?/, ""); sub(/^help: /, ""); print } + ' "$1" +} + +usage() { + echo "Usage: dev [args]" + echo + echo "Commands:" + for script in "$BINDIR"/dev-*; do + [[ -x $script ]] || continue + printf " %-18s %s\n" "${script##*/dev-}" "$(doc_block "$script" | head -n 1)" + done + echo + echo "Run 'dev help ' for more detail on a single command." +} + +die_unknown() { + echo "Unknown command: $1" >&2 + echo >&2 + usage >&2 + exit 1 +} + +command_help() { + local name="$1" + local script="$BINDIR/dev-$name" + + if [[ ! -x $script ]]; then + die_unknown "$name" + fi + + doc_block "$script" +} + +SUBCOMMAND="${1:-}" + +case "$SUBCOMMAND" in +"" | -h | --help) + usage + exit 0 + ;; +help) + if [[ -n ${2:-} ]]; then + command_help "$2" + else + usage + fi + exit 0 + ;; +esac + +shift +COMMAND="$BINDIR/dev-$SUBCOMMAND" + +if [[ ! -x $COMMAND ]]; then + die_unknown "$SUBCOMMAND" +fi + +exec "$COMMAND" "$@" From 19c38e138fa390b60a65b4bb38fbf7162edbf7e4 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:52 +0100 Subject: [PATCH 03/32] add shared test scaffolding for stubbing the tools the scripts call --- tests/helpers.sh | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tests/helpers.sh diff --git a/tests/helpers.sh b/tests/helpers.sh new file mode 100644 index 0000000..708b2fa --- /dev/null +++ b/tests/helpers.sh @@ -0,0 +1,45 @@ +# shellcheck shell=bash +# +# Shared scaffolding for the tests. Assertions report and carry on rather than aborting, so one +# run tells you everything that's broken instead of only the first thing. + +FAILED=0 + +# Creates a temporary working directory which cleans itself up, with a stub directory already at +# the front of $PATH for fake versions of git, ssh, op and friends. +make_workdir() { + WORKDIR=$(mktemp -d) + trap 'rm -rf "$WORKDIR"' EXIT + + mkdir -p "$WORKDIR/stub" + export PATH="$WORKDIR/stub:$PATH" +} + +# Writes an executable stub into the stub directory, reading its body from stdin. +write_stub() { + cat >"$WORKDIR/stub/$1" + chmod +x "$WORKDIR/stub/$1" +} + +expect() { + local description="$1" expected="$2" actual="$3" + + if [ "$expected" != "$actual" ]; then + fail "$description" + echo " expected: $expected" + echo " actual: $actual" + fi +} + +fail() { + echo "FAIL: $1" + FAILED=1 +} + +finish() { + if [ "$FAILED" != 0 ]; then + exit 1 + fi + + echo "PASS: $1" +} From 3b279b3afee2029f6b346fb27996685cb1bb83d6 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:52 +0100 Subject: [PATCH 04/32] default dev-aws-login to the devsoc profile --- bin/dev-aws-login | 15 ++++++++++++++- tests/test-aws-login.sh | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100755 tests/test-aws-login.sh diff --git a/bin/dev-aws-login b/bin/dev-aws-login index 6c76d03..bc45a25 100755 --- a/bin/dev-aws-login +++ b/bin/dev-aws-login @@ -2,4 +2,17 @@ set -euo pipefail IFS=$'\n\t' -exec aws-vault login -- "$@" +# help: Open the AWS console via aws-vault +# +# Usage: +# dev aws-login [profile] +# +# Defaults to the profile in $AWS_VAULT_PROFILE, or "devsoc". + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +DEFAULT_PROFILE="${AWS_VAULT_PROFILE:-devsoc}" + +exec aws-vault login -- "${@:-$DEFAULT_PROFILE}" diff --git a/tests/test-aws-login.sh b/tests/test-aws-login.sh new file mode 100755 index 0000000..daac170 --- /dev/null +++ b/tests/test-aws-login.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# dev-aws-login only picks a profile, but getting that wrong logs you into the wrong AWS account. + +BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub aws-vault <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +echo "$*" +STUB + +expect "no arguments uses the default profile" \ + "login -- devsoc" "$( + unset AWS_VAULT_PROFILE + "$BINDIR/dev" aws-login + )" + +expect "AWS_VAULT_PROFILE overrides the default" \ + "login -- someotherprofile" "$(AWS_VAULT_PROFILE=someotherprofile "$BINDIR/dev" aws-login)" + +expect "an explicit profile wins over everything" \ + "login -- explicitprofile" \ + "$(AWS_VAULT_PROFILE=someotherprofile "$BINDIR/dev" aws-login explicitprofile)" + +finish "the right aws-vault profile is chosen" From 6a9383b08db1f74e273ed542a5d0048bbf3a18ef Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:52 +0100 Subject: [PATCH 05/32] teach dev-clone about urls, non-python projects and vscode workspaces --- bin/dev-clone | 140 ++++++++++++++++++++++++++++++++++++-------- tests/test-clone.sh | 121 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 235 insertions(+), 26 deletions(-) create mode 100755 tests/test-clone.sh diff --git a/bin/dev-clone b/bin/dev-clone index ef76701..c649035 100755 --- a/bin/dev-clone +++ b/bin/dev-clone @@ -1,33 +1,109 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' -# shellcheck disable=SC1090 -source "$VIRTUALENVWRAPPER_SCRIPT" +# help: Clone a repo and set up virtualenvwrapper for it +# +# Usage: +# dev clone [--vscode] [org/]repo +# +# Accepts a bare repo name, "org/repo", or a URL pasted from the browser. Requires +# virtualenvwrapper, with $PROJECT_HOME set. The Python version comes from .python-version or +# tox.ini's basepython, and repos which don't look like Python projects skip the virtualenv. +# +# --vscode also writes a .code-workspace file pointing at the project's interpreter, and hides it +# from git. + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +DEFAULT_ORG="developersociety" + +MAKE_VSCODE_WORKSPACE=0 +if [[ ${1:-} == "--vscode" ]]; then + MAKE_VSCODE_WORKSPACE=1 + shift +fi if [ $# != 1 ]; then - echo "Must specify repo name to clone" + echo "Usage: dev clone [--vscode] [org/]repo" exit 1 fi -# Handle org/repo, and repo -if [[ $1 == *"/"* ]]; then - REPO_NAME="$1" - PROJECT_NAME="${1##*/}" +if [ -z "${PROJECT_HOME:-}" ] || [ -z "${VIRTUALENVWRAPPER_SCRIPT:-}" ]; then + echo "\$PROJECT_HOME and \$VIRTUALENVWRAPPER_SCRIPT must be set." + echo "Is virtualenvwrapper installed and set up in your shell?" + exit 1 +fi + +# shellcheck disable=SC1090 +source "$VIRTUALENVWRAPPER_SCRIPT" + +# Accept anything you might have in your clipboard: repo, org/repo, or a URL from the browser. +REPO_ARG="$1" +REPO_ARG="${REPO_ARG#https://github.com/}" +REPO_ARG="${REPO_ARG#git@github.com:}" +REPO_ARG="${REPO_ARG%/}" +REPO_ARG="${REPO_ARG%.git}" + +if [[ $REPO_ARG == *"/"* ]]; then + REPO_NAME="$REPO_ARG" else - REPO_NAME="developersociety/$1" - PROJECT_NAME="$1" + REPO_NAME="$DEFAULT_ORG/$REPO_ARG" fi +PROJECT_NAME="${REPO_NAME##*/}" GIT_URI="git@github.com:$REPO_NAME.git" PROJECT_DIR="$PROJECT_HOME/$PROJECT_NAME" +VENV_DIR="${WORKON_HOME:-$HOME/.virtualenvs}/$PROJECT_NAME" -if [ -a "$PROJECT_DIR" ]; then +if [ -e "$PROJECT_DIR" ]; then echo "Target directory already exists:" echo " $PROJECT_DIR" exit 1 fi +is_python_project() { + [ -f tox.ini ] || [ -f pyproject.toml ] || [ -f requirements.txt ] || [ -f .python-version ] +} + +project_python_version() { + # Projects pin their Python version in whichever place was fashionable when they started. + if [ -f .python-version ]; then + head -n 1 .python-version + elif [ -f tox.ini ]; then + sed -n -e 's/^[[:space:]]*basepython[[:space:]]*=[[:space:]]*python//p' tox.ini | head -n 1 + fi +} + +write_vscode_workspace() { + local workspace_file="$PROJECT_DIR/$PROJECT_NAME.code-workspace" + local interpreter_setting="" + + if [ -x "$VENV_DIR/bin/python" ]; then + interpreter_setting="\"python.defaultInterpreterPath\": \"$VENV_DIR/bin/python\"" + fi + + cat >"$workspace_file" <>"$PROJECT_DIR/.git/info/exclude" + + echo "VS Code workspace written to: $workspace_file" +} + echo "I'm going to clone: $GIT_URI" echo "Into this directory: $PROJECT_DIR" echo "And setup virtualenvwrapper for you." @@ -35,23 +111,35 @@ echo echo "Press Enter to continue..." read -r -mkdir "$PROJECT_DIR" +git clone "$GIT_URI" "$PROJECT_DIR" cd "$PROJECT_DIR" -git clone "$GIT_URI" . - -# mkproject fails with super strict mode - so we need to allow unbound variables at this point -set +u - -if grep --fixed-strings --silent "basepython" tox.ini; -then - PYTHON_VERSION=$(sed -e 's/basepython[[:space:]]=[[:space:]]//' -e 'tx' -e 'd' -e ':x' tox.ini | head -n 1) - PYTHON_VERSION_NUMBER=${PYTHON_VERSION/python/} - LATEST_PYTHON=$(pyenv latest "$PYTHON_VERSION_NUMBER") - VIRTUALENV_EXE=$(PYENV_VERSION=$LATEST_PYTHON pyenv which virtualenv) - VIRTUALENVWRAPPER_VIRTUALENV=$VIRTUALENV_EXE mkproject --force --python="$PYTHON_VERSION" "$PROJECT_NAME" + +if is_python_project; then + # mkproject fails with super strict mode - so we need to allow unbound variables at this point + set +u + + PYTHON_VERSION=$(project_python_version) + + if [ -n "$PYTHON_VERSION" ] && command -v pyenv >/dev/null; then + LATEST_PYTHON=$(pyenv latest "$PYTHON_VERSION") + PYTHON_EXE=$(PYENV_VERSION=$LATEST_PYTHON pyenv which python) + VIRTUALENV_EXE=$(PYENV_VERSION=$LATEST_PYTHON pyenv which virtualenv) + VIRTUALENVWRAPPER_VIRTUALENV=$VIRTUALENV_EXE mkproject --force --python="$PYTHON_EXE" \ + "$PROJECT_NAME" + else + mkproject --force "$PROJECT_NAME" + fi + + set -u + FINAL_MESSAGE="Done - to activate this project: workon $PROJECT_NAME" else - mkproject --force "$PROJECT_NAME" + FINAL_MESSAGE="Done - this doesn't look like a Python project, so no virtualenv was created." fi echo -echo "Done - to active this project: workon $PROJECT_NAME" + +if [ "$MAKE_VSCODE_WORKSPACE" = 1 ]; then + write_vscode_workspace +fi + +echo "$FINAL_MESSAGE" diff --git a/tests/test-clone.sh b/tests/test-clone.sh new file mode 100755 index 0000000..1d6ec80 --- /dev/null +++ b/tests/test-clone.sh @@ -0,0 +1,121 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# dev-clone works out the repo URL, whether the project needs a virtualenv, and which Python to +# build it with. All of that is easy to break silently, so it runs here against stubbed git, +# pyenv and virtualenvwrapper - no network, no real virtualenvs. + +BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +REAL_GIT=$(command -v git) +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +mkdir -p "$WORKDIR/fixtures/empty" "$WORKDIR/fixtures/python" "$WORKDIR/fixtures/toxini" \ + "$WORKDIR/projects" "$WORKDIR/virtualenvs" + +touch "$WORKDIR/fixtures/empty/README.md" +touch "$WORKDIR/fixtures/python/pyproject.toml" +printf '[testenv]\nbasepython = python3.11\n' >"$WORKDIR/fixtures/toxini/tox.ini" + +write_stub git < "\$STUB_CLONE_URI" + mkdir -p "\$3" + cp -R "\$STUB_FIXTURE"/. "\$3"/ + "$REAL_GIT" init --quiet "\$3" + exit 0 +fi +STUB + +write_stub pyenv <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +case "${1:-}" in + latest) echo "$2.99" ;; + which) echo "/fake/bin/$2" ;; + *) exit 1 ;; +esac +STUB + +cat >"$WORKDIR/virtualenvwrapper.sh" <<'STUB' +mkproject() { + # "$@" rather than "$*", as dev-clone sets IFS to newline and tab. + echo "$@" > "$STUB_MKPROJECT_ARGS" +} +STUB + +export PROJECT_HOME="$WORKDIR/projects" +export WORKON_HOME="$WORKDIR/virtualenvs" +export VIRTUALENVWRAPPER_SCRIPT="$WORKDIR/virtualenvwrapper.sh" +export STUB_CLONE_URI="$WORKDIR/clone-uri" +export STUB_MKPROJECT_ARGS="$WORKDIR/mkproject-args" + +run_clone() { + # The confirmation prompt reads a line, so give it one. + export STUB_FIXTURE="$WORKDIR/fixtures/$1" + shift + rm -f "$STUB_CLONE_URI" "$STUB_MKPROJECT_ARGS" + printf '\n' | "$BINDIR/dev" clone "$@" >/dev/null +} + +mkproject_args() { + if [ -f "$STUB_MKPROJECT_ARGS" ]; then + cat "$STUB_MKPROJECT_ARGS" + else + echo "no mkproject" + fi +} + +run_clone empty someproject +expect "a bare name is assumed to be a developersociety repo" \ + "git@github.com:developersociety/someproject.git" "$(cat "$STUB_CLONE_URI")" +expect "a project with no Python files gets no virtualenv" "no mkproject" "$(mkproject_args)" + +run_clone empty someorg/otherproject +expect "an org/repo argument is used as given" \ + "git@github.com:someorg/otherproject.git" "$(cat "$STUB_CLONE_URI")" + +run_clone empty https://github.com/someorg/urlproject +expect "a browser URL is turned into an SSH remote" \ + "git@github.com:someorg/urlproject.git" "$(cat "$STUB_CLONE_URI")" + +run_clone python pythonproject +expect "a project with a pyproject.toml gets a virtualenv" \ + "--force pythonproject" "$(mkproject_args)" + +run_clone toxini toxproject +expect "tox.ini's basepython picks the interpreter" \ + "--force --python=/fake/bin/python toxproject" "$(mkproject_args)" + +# The workspace points at the virtualenv's interpreter, so it has to exist by the time it's read. +mkdir -p "$WORKON_HOME/codeproject/bin" +printf '#!/bin/sh\n' >"$WORKON_HOME/codeproject/bin/python" +chmod +x "$WORKON_HOME/codeproject/bin/python" + +run_clone python --vscode codeproject +WORKSPACE_FILE="$PROJECT_HOME/codeproject/codeproject.code-workspace" + +if [ ! -f "$WORKSPACE_FILE" ]; then + fail "--vscode didn't write a workspace file" +else + expect "the workspace points at the project's interpreter" \ + "1" "$(grep -c "$WORKON_HOME/codeproject/bin/python" "$WORKSPACE_FILE")" + expect "the workspace file is hidden from git" \ + "1" "$(grep -c "codeproject.code-workspace" "$PROJECT_HOME/codeproject/.git/info/exclude")" +fi + +run_clone python plainproject +if [ -f "$PROJECT_HOME/plainproject/plainproject.code-workspace" ]; then + fail "a workspace file was written without --vscode" +fi + +if "$BINDIR/dev" clone someproject >/dev/null 2>&1; then + fail "cloning into an existing directory should exit non-zero" +fi + +finish "repo names, Python detection and the VS Code workspace all behave" From e655b5277682fe7f17bc3dd0825bcfc4b4a74375 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 06/32] add tofu env for reading and setting project env vars --- bin/dev-tofu | 132 ++++++++++++++++++++++++++++++++++++++++++++- tests/test-tofu.sh | 108 +++++++++++++++++++++++++++++++++++++ 2 files changed, 239 insertions(+), 1 deletion(-) create mode 100755 tests/test-tofu.sh diff --git a/bin/dev-tofu b/bin/dev-tofu index b2db1f2..0aa6306 100755 --- a/bin/dev-tofu +++ b/bin/dev-tofu @@ -2,4 +2,134 @@ set -euo pipefail IFS=$'\n\t' -exec aws-vault exec devsoc-tofu -- tofu "$@" +# help: Run tofu with the devsoc-tofu AWS profile, and manage project env vars +# +# Usage: +# dev tofu Run tofu, initialising the directory first if needed +# dev tofu all Run tofu in every project directory, one at a time +# dev tofu env List the project's env vars and their values +# dev tofu env NAME Print the value of a single env var +# dev tofu env set NAME [VALUE] Create or replace an env var, prompting if no value given +# +# Env vars live in the tofu state as "random_password" resources declared in the project's +# envvars.tf, so "env set" removes and re-imports the resource rather than applying a change. +# A "dev tofu apply" is still needed afterwards to get the new value onto the running service. +# +# Set $AWS_VAULT_PROFILE to use a profile other than devsoc-tofu. Use "tofu -help" for tofu's own +# help, as "--help" is handled here. + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +PROFILE="${AWS_VAULT_PROFILE:-devsoc-tofu}" + +tofu_exec() { + aws-vault exec "$PROFILE" -- tofu "$@" +} + +ensure_initialised() { + if [ ! -d .terraform ]; then + echo "No .terraform directory found - running 'tofu init' first." + tofu_exec init + fi +} + +# Env vars are named in upper case, which is what separates them from the random_password +# resources tofu uses internally for things like database passwords. +# ponytail: naming convention, not a real marker. Tag the resources if it ever mis-sorts one. +env_list() { + tofu_exec show -json | jq -r ' + .values.root_module.resources[] + | select(.type == "random_password") + | select(.name | test("^[A-Z][A-Z0-9_]*$")) + | "\(.name)=\(.values.result)" + ' +} + +env_get() { + local name="$1" + local value + + value=$(env_list | sed -n -e "s/^$name=//p") + + if [ -z "$value" ]; then + echo "No env var called '$name' in this project's state." >&2 + exit 1 + fi + + echo "$value" +} + +env_set() { + local name="$1" + local value="${2:-}" + + if [ -z "$value" ]; then + read -r -s -p "Value for $name: " value + echo + fi + + # A variable already in the state has to be removed before it can be re-imported. + if tofu_exec state list "random_password.$name" 2>/dev/null | grep -q .; then + tofu_exec state rm "random_password.$name" + fi + + tofu_exec import "random_password.$name" "$value" + + echo + echo "Imported $name. Run 'dev tofu apply' to roll it out." +} + +run_env_command() { + ensure_initialised + + local action="${1:-}" + + case "$action" in + "") + env_list + ;; + set) + if [ $# -lt 2 ]; then + echo "Usage: dev tofu env set NAME [VALUE]" >&2 + exit 1 + fi + env_set "$2" "${3:-}" + ;; + *) + env_get "$action" + ;; + esac +} + +run_in_every_project() { + # Projects are the directories holding their own tofu.tf, which is what allthetofu.sh used to + # find. Run them one at a time so apply's confirmation prompts stay readable. + local project + + for project in */; do + if [ ! -f "$project/tofu.tf" ]; then + continue + fi + + echo "=== ${project%/} ===" + (cd "$project" && ensure_initialised && tofu_exec "$@") + echo + done +} + +case "${1:-}" in +env) + shift + run_env_command "$@" + ;; +all) + shift + run_in_every_project "$@" + ;; +*) + ensure_initialised + exec aws-vault exec "$PROFILE" -- tofu "$@" + ;; +esac diff --git a/tests/test-tofu.sh b/tests/test-tofu.sh new file mode 100755 index 0000000..1afb08e --- /dev/null +++ b/tests/test-tofu.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# "dev tofu env" picks env vars out of the tofu state by name and has to leave alone the +# random_password resources tofu uses internally, and setting one has to remove it from the state +# before re-importing it. "dev tofu all" has to visit every project directory. Runs against a +# stubbed aws-vault, so no AWS credentials are involved. + +BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +cat >"$WORKDIR/state.json" <<'JSON' +{ + "values": { + "root_module": { + "resources": [ + {"type": "random_password", "name": "SENTRY_AUTH_TOKEN", + "values": {"result": "sentry-secret"}}, + {"type": "random_password", "name": "GEOAPIFY_API_KEY", + "values": {"result": "geoapify-secret"}}, + {"type": "random_password", "name": "db_admin_password", + "values": {"result": "internal-secret"}}, + {"type": "aws_instance", "name": "SOMETHING_ELSE", "values": {"result": "not-a-var"}} + ] + } + } +} +JSON + +write_stub aws-vault <<'STUB' +#!/usr/bin/env bash +set -euo pipefail + +# Called as: aws-vault exec PROFILE -- tofu +shift 3 +echo "$* [$(basename "$PWD")]" >> "$STUB_TOFU_LOG" + +case "${2:-}" in + show) + cat "$STUB_STATE_JSON" + ;; + state) + # Only the variables named in $STUB_EXISTING_VARS are already in the state. + if [ "${3:-}" = "list" ]; then + for existing in ${STUB_EXISTING_VARS:-}; do + if [ "random_password.$existing" = "${4:-}" ]; then + echo "${4:-}" + fi + done + fi + ;; +esac +STUB + +export STUB_STATE_JSON="$WORKDIR/state.json" +export STUB_TOFU_LOG="$WORKDIR/tofu.log" +export STUB_EXISTING_VARS="" + +# An initialised directory, so the tools don't try to run "tofu init". +mkdir -p "$WORKDIR/project/.terraform" +cd "$WORKDIR/project" + +expect "only upper case variables are listed" \ + $'SENTRY_AUTH_TOKEN=sentry-secret\nGEOAPIFY_API_KEY=geoapify-secret' \ + "$("$BINDIR/dev" tofu env)" + +expect "a single variable can be fetched" \ + "geoapify-secret" "$("$BINDIR/dev" tofu env GEOAPIFY_API_KEY)" + +if "$BINDIR/dev" tofu env NO_SUCH_VARIABLE >/dev/null 2>&1; then + fail "asking for a missing env var should exit non-zero" +fi + +if "$BINDIR/dev" tofu env db_admin_password >/dev/null 2>&1; then + fail "tofu's internal passwords shouldn't be reachable as env vars" +fi + +# Replacing a variable which is already in the state has to remove it before importing. +: >"$STUB_TOFU_LOG" +STUB_EXISTING_VARS="SENTRY_AUTH_TOKEN" \ + "$BINDIR/dev" tofu env set SENTRY_AUTH_TOKEN new-value >/dev/null +expect "replacing a variable removes it from the state, then imports it" \ + $'tofu state rm random_password.SENTRY_AUTH_TOKEN\ntofu import random_password.SENTRY_AUTH_TOKEN new-value' \ + "$(grep -E "state rm|import" "$STUB_TOFU_LOG" | sed -e 's/ \[.*\]$//')" + +# A variable which isn't in the state yet is imported without a pointless removal. +: >"$STUB_TOFU_LOG" +"$BINDIR/dev" tofu env set BRAND_NEW_TOKEN new-value >/dev/null +expect "a brand new variable is imported without a state removal" \ + "tofu import random_password.BRAND_NEW_TOKEN new-value" \ + "$(grep -E "state rm|import" "$STUB_TOFU_LOG" | sed -e 's/ \[.*\]$//')" + +# "all" visits directories holding a tofu.tf, and nothing else. +mkdir -p "$WORKDIR/repo/alpha/.terraform" "$WORKDIR/repo/beta/.terraform" "$WORKDIR/repo/modules" +touch "$WORKDIR/repo/alpha/tofu.tf" "$WORKDIR/repo/beta/tofu.tf" +cd "$WORKDIR/repo" + +: >"$STUB_TOFU_LOG" +"$BINDIR/dev" tofu all plan >/dev/null +expect "every project directory is visited, and nothing else" \ + $'tofu plan [alpha]\ntofu plan [beta]' \ + "$(cat "$STUB_TOFU_LOG")" + +finish "env vars listed, fetched and imported, and 'all' visits every project" From 8a20e09cc6fe9205d40f5177aa145742ae1feae6 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 07/32] delete squash-merged branches too --- bin/dev-clean-branches | 72 ++++++++++++++++++++++++++++++++---- tests/test-clean-branches.sh | 64 ++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 8 deletions(-) create mode 100755 tests/test-clean-branches.sh diff --git a/bin/dev-clean-branches b/bin/dev-clean-branches index f7dd0c3..f49bd40 100755 --- a/bin/dev-clean-branches +++ b/bin/dev-clean-branches @@ -1,7 +1,27 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' +# help: Delete merged local branches, including squash-merged ones, and prune remotes +# +# Usage: +# dev clean-branches [--yes] +# +# Deletes local branches whose changes have landed on the default branch. Squash-merged branches +# are found too, which "git branch --merged" cannot do on its own. main, master, dev and the +# repo's own default branch are never deleted. + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +PROTECTED_BRANCHES="^main$|^master$|^dev$" + +ASSUME_YES=0 +if [[ ${1:-} == "-y" || ${1:-} == "--yes" ]]; then + ASSUME_YES=1 +fi + # If the remote repo was added without the usual clone, then HEAD might be missing. A quick fix # can restore HEAD to the expected branch. if [[ ! -f .git/refs/remotes/origin/HEAD ]]; then @@ -9,21 +29,57 @@ if [[ ! -f .git/refs/remotes/origin/HEAD ]]; then fi DEFAULT_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD | sed -e "s|^refs/remotes/origin/||") -BRANCHES=$(git branch --merged "$DEFAULT_BRANCH" --format "%(refname:short)" | grep -v -e "^main$" -e "^master$" -e "^dev$" -e "^${DEFAULT_BRANCH}$") -if [[ -n $BRANCHES ]]; then +# Compare against the remote branch rather than the local one, which may be stale or absent. +BASE_BRANCH="origin/$DEFAULT_BRANCH" + +is_squash_merged() { + # A squash-merge leaves no ancestry behind, so "git branch --merged" cannot see it. Replaying + # the branch's tree as a single commit on top of the merge base gives git something it can + # recognise: if that commit is already present in the base branch, the changes have landed. + local branch="$1" + local merge_base squashed + + merge_base=$(git merge-base "$BASE_BRANCH" "$branch") + squashed=$(git commit-tree "$branch^{tree}" -p "$merge_base" -m "squash-merge check") + + ! git cherry "$BASE_BRANCH" "$squashed" | grep -q "^+" +} + +BRANCHES=() +for BRANCH in $(git branch --format "%(refname:short)"); do + if [[ $BRANCH =~ $PROTECTED_BRANCHES ]] || [[ $BRANCH == "$DEFAULT_BRANCH" ]]; then + continue + fi + + if git merge-base --is-ancestor "$BRANCH" "$BASE_BRANCH" || is_squash_merged "$BRANCH"; then + BRANCHES+=("$BRANCH") + fi +done + +if [[ ${#BRANCHES[@]} -gt 0 ]]; then echo "Will remove the following branches:" echo - echo "$BRANCHES" + printf '%s\n' "${BRANCHES[@]}" echo - echo "Press Enter to delete the above branches, or -c to bail" - read -r - echo "$BRANCHES" | xargs git branch -d + if [[ $ASSUME_YES != 1 ]]; then + echo "Press Enter to delete the above branches, or -c to bail" + read -r + fi + + # Git refuses to delete the branch you are standing on. + if [[ " ${BRANCHES[*]} " == *" $(git branch --show-current) "* ]]; then + git switch "$DEFAULT_BRANCH" + fi + + # -D rather than -d, because squash-merged branches are not ancestors of the base branch and + # git would refuse to delete them. is_squash_merged has already confirmed the work landed. + git branch -D "${BRANCHES[@]}" echo "Done." else - echo "No local branches needing" + echo "No local branches need removing" fi echo diff --git a/tests/test-clean-branches.sh b/tests/test-clean-branches.sh new file mode 100755 index 0000000..3333dec --- /dev/null +++ b/tests/test-clean-branches.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# Checks that dev-clean-branches deletes merged and squash-merged branches while leaving +# unmerged and protected ones alone. Squash-merge detection is the only non-obvious logic in +# these tools, and it silently does nothing when it breaks. + +CLEAN_BRANCHES="$(cd "$(dirname "$0")/../bin" && pwd)/dev-clean-branches" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +export GIT_AUTHOR_NAME="Test" GIT_AUTHOR_EMAIL="test@example.com" +export GIT_COMMITTER_NAME="Test" GIT_COMMITTER_EMAIL="test@example.com" + +git init --quiet --bare --initial-branch=main "$WORKDIR/origin.git" +git clone --quiet "$WORKDIR/origin.git" "$WORKDIR/repo" 2>/dev/null +cd "$WORKDIR/repo" + +echo "start" >file.txt +git add file.txt +git commit --quiet -m "Initial commit" +git push --quiet origin main + +git switch --quiet -c merged-branch +echo "merged" >merged.txt +git add merged.txt +git commit --quiet -m "Merged work" + +git switch --quiet -c squashed-branch main +echo "squashed one" >squashed.txt +git add squashed.txt +git commit --quiet -m "Squashed work, part one" +echo "squashed two" >>squashed.txt +git commit --quiet -am "Squashed work, part two" + +git switch --quiet -c unmerged-branch main +echo "unmerged" >unmerged.txt +git add unmerged.txt +git commit --quiet -m "Unmerged work" + +git switch --quiet main +git merge --quiet --no-ff -m "Merge merged-branch" merged-branch >/dev/null +git merge --quiet --squash squashed-branch >/dev/null 2>&1 +git commit --quiet -m "Squash merge of squashed-branch" +git push --quiet origin main + +"$CLEAN_BRANCHES" --yes >/dev/null + +expect "merged and squash-merged branches go, the unmerged one stays" \ + "main unmerged-branch " "$(git branch --format "%(refname:short)" | sort | tr '\n' ' ')" + +# A second run has nothing to delete, which used to abort the script when grep found no matches. +git switch --quiet main +git branch --quiet -D unmerged-branch +SECOND_RUN=$("$CLEAN_BRANCHES" --yes) + +if [[ $SECOND_RUN != *"No local branches need removing"* ]]; then + fail "expected a clean repo to report nothing to remove, got: $SECOND_RUN" +fi + +finish "merged and squash-merged branches removed, and a clean repo says so" From 98a5ad65c16ec38ede20ff87285fd34361575015 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 08/32] unlock several servers, waiting for each one to boot --- bin/dev-unlock-server | 76 +++++++++++++++++++++++++++++++----- tests/test-unlock-server.sh | 78 +++++++++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 10 deletions(-) create mode 100755 tests/test-unlock-server.sh diff --git a/bin/dev-unlock-server b/bin/dev-unlock-server index 4be6326..43b6c5c 100755 --- a/bin/dev-unlock-server +++ b/bin/dev-unlock-server @@ -2,15 +2,71 @@ set -euo pipefail IFS=$'\n\t' -if [[ $# -ne 1 ]]; then - echo "Usage: dev-unlock-server hostname.devsoc.org" >&2 +# help: Unlock the encrypted root filesystem on one or more servers +# +# Usage: +# dev unlock-server hostname.devsoc.org [hostname.devsoc.org ...] +# +# Reads each server's passphrase from 1Password and sends it to the initramfs SSH server, then +# waits for the machine to finish booting before moving on to the next one. Set +# $DEV_UNLOCK_TIMEOUT to wait longer than the default 180 seconds for a slow server. + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +OP_VAULT="aizi3l3vxjc52mboshwj7bbytq" +KNOWN_HOSTS_FILE="$HOME/.ssh/known_hosts.cryptroot-unlock" +BOOT_TIMEOUT_SECONDS="${DEV_UNLOCK_TIMEOUT:-180}" +BOOT_POLL_SECONDS=5 + +if [ $# -lt 1 ]; then + echo "Usage: dev unlock-server hostname.devsoc.org [hostname.devsoc.org ...]" + exit 1 +fi + +if ! op account get >/dev/null 2>&1; then + echo "1Password CLI not usable. Install it with 'brew install --cask 1password-cli'," + echo "or sign in with: eval \$(op signin)" exit 1 fi -HOST="$1" - -LUKS_PASSPHRASE=$(op read "op://aizi3l3vxjc52mboshwj7bbytq/$HOST/password") -echo -n "$LUKS_PASSPHRASE" | \ - ssh -o UserKnownHostsFile="$HOME/.ssh/known_hosts.cryptroot-unlock" \ - -o StrictHostKeyChecking=accept-new \ - -o BatchMode=yes \ - "root@$HOST" cryptroot-unlock + +send_passphrase() { + local host="$1" + local passphrase + passphrase=$(op read "op://$OP_VAULT/$host/password") + + # The initramfs SSH server has its own host key, so it gets its own known_hosts file. + echo -n "$passphrase" | + ssh -o UserKnownHostsFile="$KNOWN_HOSTS_FILE" \ + -o StrictHostKeyChecking=accept-new \ + -o BatchMode=yes \ + "root@$host" cryptroot-unlock +} + +wait_for_boot() { + # The initramfs SSH server disappears the moment the disk unlocks, so reaching the real host's + # SSH is what actually confirms the machine finished booting. + local host="$1" + local deadline=$((SECONDS + BOOT_TIMEOUT_SECONDS)) + + while [ $SECONDS -lt $deadline ]; do + if ssh -o BatchMode=yes -o ConnectTimeout=5 "$host" true 2>/dev/null; then + return 0 + fi + sleep "$BOOT_POLL_SECONDS" + done + + return 1 +} + +for HOST in "$@"; do + echo "Unlocking $HOST..." + send_passphrase "$HOST" + + if wait_for_boot "$HOST"; then + echo "$HOST is up." + else + echo "$HOST did not come back within ${BOOT_TIMEOUT_SECONDS}s - check it manually." >&2 + fi +done diff --git a/tests/test-unlock-server.sh b/tests/test-unlock-server.sh new file mode 100755 index 0000000..2614da9 --- /dev/null +++ b/tests/test-unlock-server.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# dev-unlock-server hands a passphrase to a server's initramfs and then waits for it to boot. +# Runs against stubbed op, ssh and sleep, so nothing is contacted and nothing actually waits. + +BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub op <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +case "${1:-}" in + account) [ -z "${STUB_OP_SIGNED_OUT:-}" ] ;; + read) + echo "$2" >> "$STUB_OP_LOG" + echo "passphrase-for-$2" + ;; +esac +STUB + +write_stub ssh <<'STUB' +#!/usr/bin/env bash +set -euo pipefail + +command="${*: -1}" +target="${*: -2:1}" + +if [ "$command" = "cryptroot-unlock" ]; then + read -r passphrase || true + echo "unlock $target $passphrase" >> "$STUB_SSH_LOG" + exit 0 +fi + +echo "boot-check $target" >> "$STUB_SSH_LOG" +case " ${STUB_UP_HOSTS:-} " in + *" $target "*) exit 0 ;; +esac +exit 1 +STUB + +write_stub sleep <<'STUB' +#!/usr/bin/env bash +exit 0 +STUB + +export STUB_OP_LOG="$WORKDIR/op.log" +export STUB_SSH_LOG="$WORKDIR/ssh.log" + +if STUB_OP_SIGNED_OUT=1 "$BINDIR/dev" unlock-server one.example >/dev/null 2>&1; then + fail "being signed out of 1Password should exit non-zero" +fi + +: >"$STUB_OP_LOG" +: >"$STUB_SSH_LOG" +STUB_UP_HOSTS="one.example two.example" \ + "$BINDIR/dev" unlock-server one.example two.example >/dev/null + +expect "each host's passphrase is read from its own 1Password item" \ + $'op://aizi3l3vxjc52mboshwj7bbytq/one.example/password\nop://aizi3l3vxjc52mboshwj7bbytq/two.example/password' \ + "$(cat "$STUB_OP_LOG")" + +expect "each host is unlocked as root and then checked for boot, in order" \ + $'unlock root@one.example passphrase-for-op://aizi3l3vxjc52mboshwj7bbytq/one.example/password\nboot-check one.example\nunlock root@two.example passphrase-for-op://aizi3l3vxjc52mboshwj7bbytq/two.example/password\nboot-check two.example' \ + "$(cat "$STUB_SSH_LOG")" + +OUTPUT=$(DEV_UNLOCK_TIMEOUT=1 STUB_UP_HOSTS="" \ + "$BINDIR/dev" unlock-server slow.example 2>&1 >/dev/null) + +if [[ $OUTPUT != *"did not come back"* ]]; then + fail "a host which never boots should warn on stderr, got: $OUTPUT" +fi + +finish "passphrases fetched per host, unlocked in order, and slow servers warn" From 1993b5a51acbe452b9c5a3f3613b911268780cb8 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 09/32] diff and back up the aws config before rewriting it --- bin/dev-update-aws-config | 57 ++++++++++++++++++++++----- tests/test-update-aws-config.sh | 68 +++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 9 deletions(-) create mode 100755 tests/test-update-aws-config.sh diff --git a/bin/dev-update-aws-config b/bin/dev-update-aws-config index bd29fcb..0271a7b 100755 --- a/bin/dev-update-aws-config +++ b/bin/dev-update-aws-config @@ -2,21 +2,60 @@ set -euo pipefail IFS=$'\n\t' -if [ $# != 1 ]; then - echo "Must specify username" +# help: Rewrite ~/.aws/config from the 1Password template +# +# Usage: +# dev update-aws-config [username] +# +# Shows a diff and asks before replacing anything. The username defaults to $USER, and the last +# 5 backups are kept alongside the config. + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +BACKUPS_TO_KEEP=5 +CONFIG_FILE="$HOME/.aws/config" + +CONFIG_USERNAME="${1:-$USER}" + +if ! op account get >/dev/null 2>&1; then + echo "1Password CLI not usable. Install it with 'brew install --cask 1password-cli'," + echo "or sign in with: eval \$(op signin)" exit 1 fi -CONFIG_USERNAME="$1" +mkdir -p "$HOME/.aws" -mkdir -p ~/.aws +# Render to a temporary file first, so a failed "op read" can't leave you with no config at all. +TMPFILE=$(mktemp) +trap 'rm -f "$TMPFILE"' EXIT -if [ -f ~/.aws/config ]; then - OLD_TIMESTAMP=$(date -u +"%Y%m%dT%H%M%SZ") - echo "Backup of existing config saved to: $HOME/.aws/config.old.$OLD_TIMESTAMP" - mv ~/.aws/config "$HOME/.aws/config.old.$OLD_TIMESTAMP" +op read "op://Shared/AWS Config Template/notesPlain" | + sed -e "s|USERNAME|$CONFIG_USERNAME|g" >"$TMPFILE" + +if [ -f "$CONFIG_FILE" ]; then + if diff -u "$CONFIG_FILE" "$TMPFILE"; then + echo "Config is already up to date for '$CONFIG_USERNAME'." + exit 0 + fi + + echo + echo "Press Enter to apply the above changes for '$CONFIG_USERNAME', or -c to bail" + read -r + + TIMESTAMP=$(date -u +"%Y%m%dT%H%M%SZ") + cp "$CONFIG_FILE" "$CONFIG_FILE.old.$TIMESTAMP" + echo "Backup of existing config saved to: $CONFIG_FILE.old.$TIMESTAMP" fi -op read "op://Shared/AWS Config Template/notesPlain" | sed -e "s|USERNAME|$CONFIG_USERNAME|g" > ~/.aws/config +mv "$TMPFILE" "$CONFIG_FILE" + +# Backups otherwise accumulate forever, one per run. +{ ls -1t "$CONFIG_FILE".old.* 2>/dev/null || true; } | + tail -n +$((BACKUPS_TO_KEEP + 1)) | + while read -r OLD_BACKUP; do + rm -f "$OLD_BACKUP" + done echo "Config file updated!" diff --git a/tests/test-update-aws-config.sh b/tests/test-update-aws-config.sh new file mode 100755 index 0000000..ced0b9f --- /dev/null +++ b/tests/test-update-aws-config.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# dev-update-aws-config replaces a file people depend on, so the parts worth checking are that it +# leaves an unchanged config alone, backs up before replacing, and doesn't hoard backups forever. +# Runs against a stubbed 1Password CLI. + +BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub op <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +case "${1:-}" in + account) exit 0 ;; + read) cat "$STUB_OP_TEMPLATE" ;; + *) exit 1 ;; +esac +STUB + +printf '[profile USERNAME]\nregion = eu-west-1\n' >"$WORKDIR/template" +export STUB_OP_TEMPLATE="$WORKDIR/template" + +mkdir -p "$WORKDIR/home" +export HOME="$WORKDIR/home" +CONFIG_FILE="$HOME/.aws/config" + +count_backups() { + find "$HOME/.aws" -name "config.old.*" | wc -l | tr -d ' ' +} + +printf '\n' | "$BINDIR/dev" update-aws-config alice >/dev/null +expect "the username is substituted into the template" \ + "[profile alice]" "$(head -n 1 "$CONFIG_FILE")" +expect "the first run leaves no backup behind" "0" "$(count_backups)" + +printf '\n' | "$BINDIR/dev" update-aws-config alice >/dev/null +expect "re-running with no changes doesn't write a backup" "0" "$(count_backups)" + +printf '\n' | "$BINDIR/dev" update-aws-config bob >/dev/null +expect "a changed config is written" "[profile bob]" "$(head -n 1 "$CONFIG_FILE")" +expect "replacing the config backs up the old one" "1" "$(count_backups)" + +# Six older backups plus the one above is over the limit, so the oldest should be dropped. +for index in 1 2 3 4 5 6; do + touch "$HOME/.aws/config.old.2020010${index}T000000Z" +done + +printf '\n' | "$BINDIR/dev" update-aws-config carol >/dev/null +expect "old backups are pruned" "5" "$(count_backups)" + +if [ -f "$HOME/.aws/config.old.20200101T000000Z" ]; then + fail "the oldest backup should have been pruned first" +fi + +# A failure reading the template must not leave the config missing or empty. +rm -f "$STUB_OP_TEMPLATE" +if printf '\n' | "$BINDIR/dev" update-aws-config dave >/dev/null 2>&1; then + fail "a failed 'op read' should exit non-zero" +fi +expect "a failed run leaves the existing config in place" \ + "[profile carol]" "$(head -n 1 "$CONFIG_FILE")" + +finish "config diffed, backed up and pruned, and survives a failed template read" From 0fe1795a2b78641c2cdbc9087d0ac3b357d26fff Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 10/32] archive the repo on github after mirroring it --- bin/dev-archive-repo | 48 +++++++++++++++++++----- tests/test-archive-repo.sh | 76 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 9 deletions(-) create mode 100755 tests/test-archive-repo.sh diff --git a/bin/dev-archive-repo b/bin/dev-archive-repo index dc7f240..3c0dfd6 100755 --- a/bin/dev-archive-repo +++ b/bin/dev-archive-repo @@ -1,20 +1,50 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' +# help: Mirror a repo to the archive server, then archive it on GitHub +# +# Usage: +# dev archive-repo [org/]repo +# +# Mirrors every branch and tag to the archive server, then archives the repo on GitHub, which +# makes it read-only. A repo name given without an org is assumed to be under developersociety. + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +DEFAULT_ORG="developersociety" +ARCHIVE_HOST="smirkenorff.devsoc.org" + if [ $# != 1 ]; then - echo "Must specify repo name to clone" + echo "Usage: dev archive-repo [org/]repo" exit 1 fi -GIT_REPO=$1 +# Handle org/repo, and repo +if [[ $1 == *"/"* ]]; then + REPO_NAME="$1" +else + REPO_NAME="$DEFAULT_ORG/$1" +fi +PROJECT_NAME="${REPO_NAME##*/}" -echo "Archiving ${GIT_REPO}" +echo "I'm going to mirror: $REPO_NAME" +echo "To the archive server: $ARCHIVE_HOST" +echo "And then archive it on GitHub, which makes it read-only." +echo +echo "Press Enter to continue, or -c to bail" +read -r TMPDIR=$(mktemp -d) +trap 'rm -rf "$TMPDIR"' EXIT + +CLONE_DIR="$TMPDIR/$PROJECT_NAME.git" + +git clone --bare "git@github.com:$REPO_NAME.git" "$CLONE_DIR" +git -C "$CLONE_DIR" push --mirror "git@$ARCHIVE_HOST:archive/$PROJECT_NAME.git" + +gh repo archive "$REPO_NAME" --yes -cd "$TMPDIR" -git clone --bare "git@github.com:developersociety/${GIT_REPO}.git" -cd "${GIT_REPO}.git" -git push --mirror "git@smirkenorff.devsoc.org:archive/${GIT_REPO}.git" -rm -rf "$TMPDIR" +echo "Done - $REPO_NAME is mirrored and archived." diff --git a/tests/test-archive-repo.sh b/tests/test-archive-repo.sh new file mode 100755 index 0000000..9b86d2b --- /dev/null +++ b/tests/test-archive-repo.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# dev-archive-repo pushes to a server and makes a GitHub repo read-only, so the interesting parts +# are that it aims at the right places and that it cleans up its temporary clone even when the +# push fails. Runs against stubbed git and gh. + +BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub git <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +echo "$*" >> "$STUB_GIT_LOG" +if [ "${1:-}" = "clone" ]; then + mkdir -p "$4" + exit 0 +fi +if [ "${3:-}" = "push" ] && [ -n "${STUB_PUSH_FAILS:-}" ]; then + echo "push refused" >&2 + exit 1 +fi +if [ "${1:-}" = "-C" ]; then + exit 0 +fi +STUB + +write_stub gh <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +echo "$*" >> "$STUB_GH_LOG" +STUB + +export STUB_GIT_LOG="$WORKDIR/git.log" +export STUB_GH_LOG="$WORKDIR/gh.log" + +# mktemp honours $TMPDIR, so pointing it somewhere known makes the cleanup checkable. +mkdir -p "$WORKDIR/tmp" +export TMPDIR="$WORKDIR/tmp" + +count_temp_entries() { + find "$TMPDIR" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ' +} + +: >"$STUB_GIT_LOG" +: >"$STUB_GH_LOG" +printf '\n' | "$BINDIR/dev" archive-repo oldproject >/dev/null + +expect "a bare name is assumed to be a developersociety repo" \ + "1" "$(grep -c "clone --bare git@github.com:developersociety/oldproject.git" "$STUB_GIT_LOG")" +expect "the mirror is pushed to the archive server" \ + "1" "$(grep -c "push --mirror git@smirkenorff.devsoc.org:archive/oldproject.git" "$STUB_GIT_LOG")" +expect "the repo is archived on GitHub afterwards" \ + "repo archive developersociety/oldproject --yes" "$(cat "$STUB_GH_LOG")" +expect "the temporary clone is cleaned up" "0" "$(count_temp_entries)" + +: >"$STUB_GIT_LOG" +: >"$STUB_GH_LOG" +printf '\n' | "$BINDIR/dev" archive-repo someorg/theirproject >/dev/null +expect "an org/repo argument is used as given" \ + "1" "$(grep -c "clone --bare git@github.com:someorg/theirproject.git" "$STUB_GIT_LOG")" +expect "the archive path uses the repo name without the org" \ + "1" "$(grep -c "archive/theirproject.git" "$STUB_GIT_LOG")" + +: >"$STUB_GH_LOG" +if printf '\n' | STUB_PUSH_FAILS=1 "$BINDIR/dev" archive-repo brokenproject >/dev/null 2>&1; then + fail "a failed push should exit non-zero" +fi +expect "a failed push doesn't archive the repo on GitHub" "" "$(cat "$STUB_GH_LOG")" +expect "a failed push still cleans up the temporary clone" "0" "$(count_temp_entries)" + +finish "mirrored and archived to the right places, and cleans up after a failure" From 98ca00c21bddc569d9ed3470c9964c37028c3818 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 11/32] confirm before uninstalling everything in the virtualenv --- bin/dev-wipeenv | 29 ++++++++++++++++-- tests/test-wipeenv.sh | 68 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 3 deletions(-) create mode 100755 tests/test-wipeenv.sh diff --git a/bin/dev-wipeenv b/bin/dev-wipeenv index 9994f8a..cc540fc 100755 --- a/bin/dev-wipeenv +++ b/bin/dev-wipeenv @@ -1,8 +1,19 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' -if [ -z "$VIRTUAL_ENV" ]; then +# help: Uninstall every package in the active virtualenv +# +# Usage: +# dev wipeenv +# +# Lists what it is about to remove and asks first. pip, setuptools and wheel are left alone. + +if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + +if [ -z "${VIRTUAL_ENV:-}" ]; then echo "Must be in a virtual env" exit 1 fi @@ -12,6 +23,18 @@ fi # # Need to make sure not to uninstall pip itself. List of things to avoid comes from docs for # "pip freeze --all" -if ! pip list --format=freeze | grep -v "^pip=\|^setuptools=\|^wheel=" | xargs pip uninstall -y; then +PACKAGES=$(pip list --format=freeze | grep -v "^pip=\|^setuptools=\|^wheel=" || true) + +if [ -z "$PACKAGES" ]; then echo "Nothing to remove" + exit 0 fi + +echo "Will uninstall the following from $VIRTUAL_ENV:" +echo +echo "$PACKAGES" +echo +echo "Press Enter to uninstall the above packages, or -c to bail" +read -r + +echo "$PACKAGES" | xargs pip uninstall -y diff --git a/tests/test-wipeenv.sh b/tests/test-wipeenv.sh new file mode 100755 index 0000000..39901e7 --- /dev/null +++ b/tests/test-wipeenv.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# dev-wipeenv uninstalls everything in sight, so the parts worth pinning down are that it refuses +# to run outside a virtualenv and that it never uninstalls pip itself. Runs against a stubbed pip. + +BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub pip <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +case "${1:-}" in + list) cat "$STUB_PIP_PACKAGES" ;; + uninstall) shift 2; echo "$*" > "$STUB_PIP_UNINSTALLED" ;; +esac +STUB + +export STUB_PIP_PACKAGES="$WORKDIR/packages" +export STUB_PIP_UNINSTALLED="$WORKDIR/uninstalled" + +# Without a virtualenv the script has to say so, not fall over on an unset variable. +expect "running outside a virtualenv explains itself" "Must be in a virtual env" \ + "$( + unset VIRTUAL_ENV + printf '\n' | "$BINDIR/dev" wipeenv 2>&1 || true + )" + +if ( + unset VIRTUAL_ENV + printf '\n' | "$BINDIR/dev" wipeenv >/dev/null 2>&1 +); then + fail "running outside a virtualenv should exit non-zero" +fi + +export VIRTUAL_ENV="$WORKDIR/fake-venv" + +cat >"$STUB_PIP_PACKAGES" <<'PACKAGES' +pip==25.0 +setuptools==80.0 +wheel==0.45 +django==5.2 +requests==2.32 +PACKAGES + +rm -f "$STUB_PIP_UNINSTALLED" +printf '\n' | "$BINDIR/dev" wipeenv >/dev/null +expect "pip, setuptools and wheel are left alone" \ + "django==5.2 requests==2.32" "$(cat "$STUB_PIP_UNINSTALLED")" + +cat >"$STUB_PIP_PACKAGES" <<'PACKAGES' +pip==25.0 +setuptools==80.0 +PACKAGES + +rm -f "$STUB_PIP_UNINSTALLED" +expect "an already-empty virtualenv says there's nothing to do" "Nothing to remove" \ + "$(printf '\n' | "$BINDIR/dev" wipeenv)" + +if [ -f "$STUB_PIP_UNINSTALLED" ]; then + fail "nothing should have been uninstalled from an empty virtualenv" +fi + +finish "refuses to run outside a virtualenv, and never uninstalls pip" From 7c410c578cf9f5400dd325c653fb62fe7683e7cc Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 12/32] run shellcheck, shfmt and the tests from make check --- .github/workflows/test.yml | 12 ++++++ Makefile | 66 ++++++++++++++++++++++++++++++ tests/test-dev.sh | 84 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 162 insertions(+) create mode 100644 .github/workflows/test.yml create mode 100644 Makefile create mode 100755 tests/test-dev.sh diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..36660e8 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,12 @@ +name: test + +on: + push: + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: make check diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a6b0c28 --- /dev/null +++ b/Makefile @@ -0,0 +1,66 @@ +SHELL=/bin/bash +.DEFAULT_GOAL := help + + +# ------------------------------- +# Common targets for Dev projects +# ------------------------------- +# +# Edit these targets so they work as expected on the current project. +# +# Remember there may be other tools which use these targets, so if a target is not suitable for +# the current project, then keep the target and simply make it do nothing. + +help: ## This help dialog. +help: help-display + +install-local: ## Install the tools needed to work on this project. +install-local: brew-install-local + +check: ## Check for any obvious errors in the project's setup. +check: lint test + +format: ## Run this project's code formatters. +format: shell-format + +lint: ## Lint the project. +lint: shell-lint shell-format-check + +test: ## Run this project's tests. +test: shell-test + + +# --------------- +# Utility targets +# --------------- +# +# Targets which are used by the common targets. You likely want to customise these per project, +# to ensure they're pointing at the correct directories, etc. + +# Installs +brew-install-local: + brew install shellcheck shfmt + + +# Shell +SHELL_SOURCES = bin/dev* tests/*.sh + +shell-lint: + shellcheck $(SHELL_SOURCES) + +shell-format: + shfmt --indent 4 --write $(SHELL_SOURCES) + +shell-format-check: + shfmt --indent 4 --diff $(SHELL_SOURCES) + +shell-test: + @for test in tests/test-*.sh; do \ + echo "== $$test"; \ + "$$test" || exit 1; \ + done + + +# Help +help-display: + @awk '/^[\-[:alnum:]]*: ##/ { split($$0, x, "##"); printf "%20s%s\n", x[1], x[2]; }' $(MAKEFILE_LIST) diff --git a/tests/test-dev.sh b/tests/test-dev.sh new file mode 100755 index 0000000..2b85051 --- /dev/null +++ b/tests/test-dev.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# The dev dispatcher finds its subcommands by looking for sibling dev-* scripts, and builds all +# of its help from the comment block in each one. Both are checked here: dispatch and discovery +# against a throwaway copy of bin with an extra command dropped in, and the documentation against +# the real commands. + +SOURCE_BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +cp -R "$SOURCE_BINDIR" "$WORKDIR/bin" +BINDIR="$WORKDIR/bin" + +cat >"$BINDIR/dev-madeupcommand" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# help: A command invented by the tests +# +# Usage: +# dev madeupcommand [args] + +echo "got: $@" +STUB +chmod +x "$BINDIR/dev-madeupcommand" + +expect "arguments are passed through untouched" \ + "got: --flag one two" "$("$BINDIR/dev" madeupcommand --flag one two)" + +if [[ $("$BINDIR/dev" help) != *"madeupcommand"* ]]; then + fail "a newly added command should appear in 'dev help' without being registered" +fi + +expect "commands are also runnable directly, without the dispatcher" \ + "got: direct" "$("$BINDIR/dev-madeupcommand" direct)" + +for INVOCATION in "" "-h" "--help" "help"; do + if [[ $("$BINDIR/dev" ${INVOCATION:+"$INVOCATION"}) != *"Usage: dev "* ]]; then + fail "'dev ${INVOCATION}' should print the usage summary" + fi +done + +if "$BINDIR/dev" no-such-command >/dev/null 2>&1; then + fail "an unknown command should exit non-zero" +fi + +if [[ $("$BINDIR/dev" no-such-command 2>&1 || true) != *"Unknown command: no-such-command"* ]]; then + fail "an unknown command should say which one it didn't recognise" +fi + +if "$BINDIR/dev" help no-such-command >/dev/null 2>&1; then + fail "'dev help' for an unknown command should exit non-zero" +fi + +# A file which isn't executable isn't a command. +touch "$BINDIR/dev-notexecutable" +if "$BINDIR/dev" notexecutable >/dev/null 2>&1; then + fail "a non-executable dev-* file shouldn't be runnable as a command" +fi + +# Every real command has to document itself, since "dev help" and each script's --help are both +# generated from the comment block in the script. A tool added without one fails here. +for SCRIPT_PATH in "$SOURCE_BINDIR"/dev-*; do + NAME="${SCRIPT_PATH##*/dev-}" + + HELP_OUTPUT=$("$SOURCE_BINDIR/dev" help "$NAME") + if [[ $HELP_OUTPUT != *"dev $NAME"* ]]; then + fail "'dev help $NAME' doesn't document a 'dev $NAME' usage line" + fi + + expect "'$NAME --help' matches 'dev help $NAME'" "$HELP_OUTPUT" "$("$SCRIPT_PATH" --help)" + + if [[ $("$SOURCE_BINDIR/dev" help) != *" $NAME "* ]]; then + fail "'$NAME' is missing from the 'dev help' summary list" + fi +done + +finish "subcommands are discovered, dispatched, and all document themselves" From 605f85acdfa0eb7d3d32adfef712ce748f74f1bc Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 13/32] replace the readme with markdown covering install and each tool --- README.md | 145 +++++++++++++++++++++++++++++++++++++++++++++++++++++ README.rst | 71 -------------------------- 2 files changed, 145 insertions(+), 71 deletions(-) create mode 100644 README.md delete mode 100644 README.rst diff --git a/README.md b/README.md new file mode 100644 index 0000000..aea9cf9 --- /dev/null +++ b/README.md @@ -0,0 +1,145 @@ +# The Developer Society — Development Tools + +Tools for making development at The Developer Society quicker, easier and less error prone. + + + +## Installation + +The tools are distributed through our own Homebrew tap. The repo is private, so Homebrew fetches +it over SSH using the GitHub key you already have set up: + +```console +$ brew tap developersociety/tools git@github.com:developersociety/tools.git +$ brew trust developersociety/tools +$ brew install devtools +``` + +The explicit git URL is required: without it Homebrew guesses a public +`https://github.com/developersociety/homebrew-tools` and gets a 404. `brew trust` is required +too, as Homebrew refuses to load formulae from third-party taps until you say so. + +If you previously added a checkout of this repo to your `$PATH`, remove that from your shell +profile. It shadows the Homebrew copies, and you'll keep running the old scripts without +noticing — `brew install` warns about this, but the warning is easy to scroll past. + +To upgrade later: + +```console +$ brew upgrade devtools +``` + +Every tool is also available as its own command, so `dev clone devsoc` and `dev-clone devsoc` do +the same thing. + +## Usage + +Run `dev help` for the list of commands, and `dev help ` for the detail on one of them. +Each command also takes `--help` directly: + +```console +$ dev help +$ dev help tofu +$ dev tofu --help +``` + +Each command explains itself, so the list below is a map rather than a manual — run +`dev help ` for the detail. + +| Command | What it does | +| --- | --- | +| `dev clone` | Clone a repo and set up virtualenvwrapper for it | +| `dev clean-branches` | Delete merged local branches, squash-merges included, and prune remotes | +| `dev tofu` | Run tofu with the devsoc-tofu profile, and manage project env vars | +| `dev aws-login` | Open the AWS console via aws-vault | +| `dev update-aws-config` | Rewrite `~/.aws/config` from the 1Password template | +| `dev unlock-server` | Unlock the encrypted root filesystem on one or more servers | +| `dev archive-repo` | Mirror a repo to the archive server, then archive it on GitHub | +| `dev wipeenv` | Uninstall every package in the active virtualenv | + +### dev tofu env + +The one command worth explaining outside its own help, because the workflow behind it isn't +obvious. A project's environment variables live in the tofu state as `random_password` resources +declared in the project's `envvars.tf`. Reading and setting them used to mean copy-pasting raw +`tofu show -json | jq ...` and `state rm` / `import` incantations from the comments at the top of +each `envvars.tf`: + +```console +$ dev tofu env # list every variable and its value +$ dev tofu env SENTRY_AUTH_TOKEN # print one value +$ dev tofu env set SENTRY_AUTH_TOKEN # prompt for the value, then import it +``` + +Setting a variable removes it from the state and re-imports it, so a `dev tofu apply` is still +needed to get the new value onto the running service. The variable has to have a +`random_password` resource in `envvars.tf` before it can be imported, and variables are told +apart from tofu's internal passwords by their upper case names. + +## Development + +Please contribute! If you find yourself needing to do the same thing over and over, or you keep +forgetting a process, or you just feel you're typing too much to do boring stuff... then create a +script to automate/help/optimise it. And then we can all benefit. + +New tools go in `bin/` named `dev-something`, with a `# help: one line summary` comment near the +top. `dev help` picks them up automatically, and Homebrew installs anything matching `bin/dev*`, +so there's no list to keep in sync. + +New commands are documented in the comment block starting at their `# help:` line. `dev help` +prints the first line in its summary list, `dev help ` prints the whole block, and each +script's `--help` prints the same thing, so there's only ever one copy of the usage text. + +The tools needed to work on this repo are shellcheck and shfmt. There's no virtualenv, because +there's no Python here: + +```console +$ make install-local +$ make format +$ make check +``` + +`make check` runs shellcheck, checks the formatting, and then runs the tests, which is what CI +runs too. `make help` lists the targets. + +### Testing locally + +For day to day work, put the checkout on your `$PATH` and run the commands straight from it: + +```console +$ export PATH="$PWD/bin:$PATH" +$ dev help +``` + +To test the Homebrew formula itself, tap your own checkout. Homebrew clones committed state, and +the formula fetches from GitHub, so point it at your working copy first and commit that change +locally — don't push it: + +```console +$ sed -i '' "s|git@github.com:developersociety/tools.git|file://$PWD|" Formula/devtools.rb +$ git commit -am "Local formula test" + +$ brew tap local/tools "$PWD" +$ brew trust local/tools +$ brew install local/tools/devtools +$ dev help +``` + +Then put it back: + +```console +$ brew uninstall devtools +$ brew untap local/tools +$ git reset --hard HEAD~1 +``` + +Note that `brew uninstall` also sweeps up orphaned dependencies, so check what it reports before +walking away from it. + +Every command has a test in `tests/`. They stub out git, ssh, pip, aws-vault, pyenv and the +1Password CLI, so they need no credentials and touch nothing outside a temporary directory. + +### Releasing + +Homebrew keys its cache on the `version` in `Formula/devtools.rb`, so shipping a release means +bumping that one line and pushing to `master`. Everyone picks it up on their next `brew upgrade`. diff --git a/README.rst b/README.rst deleted file mode 100644 index dabae77..0000000 --- a/README.rst +++ /dev/null @@ -1,71 +0,0 @@ -========================================= -The Developer Society - Development Tools -========================================= - -Tools for making development at The Developer Society quicker, easier and less error prone. - -https://github.com/developersociety/tools - -Installation -============ - -To install these tools: - -.. code:: console - - $ git clone git@github.com:developersociety/tools.git - $ cd tools/bin - $ pwd - -Add the bin directory to your ``$PATH``, by editing your ``~/.bash_profile``: - -.. code:: bash - - export PATH="/path/to/tools/bin:$PATH" - - -Usage -===== - -dev-clone ---------- - -This tool will `git-clone` a repo from Dev's github and setup virtualenvwrapper for you, with a -virtualenv and a virtualenvwrapper project for you. - -It requires virtualenvwrapper to be installed with the `$PROJECT_HOME` environment variable set -correctly. - -It will: - -* `git-clone` the repo from Dev's github -* setup virtualenv with virtualenvwrapper -* setup virtualenvwrapper project dir - -Example of use: -~~~~~~~~~~~~~~~ - -.. code-block:: console - - $ dev-clone devsoc - - -dev-wipeenv ------------ - -Removes all packages in the current virtualenv. - -Example of use: -~~~~~~~~~~~~~~~ - -.. code-block:: console - - $ dev-wipeenv - - -Development -=========== - -Please contribute! If you find yourself needing to do the same thing over and over, or you keep -forgetting a process, or you just feel you're typing too much to do boring stuff... then create a -script to automate/help/optimise it. And then we can all benefit. From 08c83e9b4951a427018e4a25bdc05832a08da050 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:05:53 +0100 Subject: [PATCH 14/32] build the formula from the tap checkout so a branch can be tested locally --- Formula/devtools.rb | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Formula/devtools.rb b/Formula/devtools.rb index 38d1487..956a794 100644 --- a/Formula/devtools.rb +++ b/Formula/devtools.rb @@ -2,10 +2,17 @@ class Devtools < Formula desc "Development tools for The Developer Society" homepage "https://github.com/developersociety/tools" - # The tap and the tools share one repo, so a pinned revision would need a second commit after - # every tag. Instead the version is what Homebrew keys its cache on: bump it to ship a release, - # and Homebrew refetches master. - url "git@github.com:developersociety/tools.git", using: :git, branch: "master" + # The tap and the tools are the same repo, so the scripts are already on disk next to this + # formula: Homebrew builds from the tap's own checkout rather than fetching from GitHub again. + # That also makes testing a branch a matter of checking it out in the tap, with no push needed. + # + # A pinned revision would need a second commit after every tag, so the version is what Homebrew + # keys its cache on: bump it to ship a release. While testing a branch, "brew fetch --force + # devtools" clears the cached clone without a bump. + TAP_CHECKOUT = Pathname.new(__dir__).parent.freeze + TAP_BRANCH = Utils.popen_read("git", "-C", TAP_CHECKOUT, "branch", "--show-current").strip.freeze + + url "file://#{TAP_CHECKOUT}", using: :git, branch: TAP_BRANCH version "1.0.0" depends_on "aws-vault" From 92dc0aa8e1a5ba931761293510cbf70c9139551a Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Thu, 10 Sep 2026 17:18:57 +0100 Subject: [PATCH 15/32] document testing a branch through the tap clone --- README.md | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index aea9cf9..fae6c48 100644 --- a/README.md +++ b/README.md @@ -111,26 +111,33 @@ $ export PATH="$PWD/bin:$PATH" $ dev help ``` -To test the Homebrew formula itself, tap your own checkout. Homebrew clones committed state, and -the formula fetches from GitHub, so point it at your working copy first and commit that change -locally — don't push it: +To test the Homebrew formula itself, tap the repo and check out the branch you want in the tap's +own clone. The formula builds from that clone, so whatever branch it's on is what gets installed +— nothing needs pushing to GitHub, and the formula needs no editing: ```console -$ sed -i '' "s|git@github.com:developersociety/tools.git|file://$PWD|" Formula/devtools.rb -$ git commit -am "Local formula test" +$ brew tap developersociety/tools git@github.com:developersociety/tools.git +$ brew trust developersociety/tools -$ brew tap local/tools "$PWD" -$ brew trust local/tools -$ brew install local/tools/devtools +$ git -C "$(brew --repo developersociety/tools)" switch some-branch +$ brew fetch --force devtools +$ brew install devtools +$ brew test devtools $ dev help ``` -Then put it back: +Then switch the tap clone back to `master` when you're done. + +Two things to know. Homebrew clones committed state, so commit before installing — staged and +unstaged work is invisible to it, and a missing file shows up as a mysteriously incomplete +install rather than an error. And it caches the clone against the formula's `version`, so +`brew fetch --force devtools` is needed between installs of the same version. + +To remove it again: ```console $ brew uninstall devtools -$ brew untap local/tools -$ git reset --hard HEAD~1 +$ brew untap developersociety/tools ``` Note that `brew uninstall` also sweeps up orphaned dependencies, so check what it reports before From 61e669b9b5729821231b62c8d828df325b8f00ae Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:31 +0100 Subject: [PATCH 16/32] use posix test brackets instead of the bash double bracket --- bin/dev | 8 ++++---- bin/dev-archive-repo | 4 ++-- bin/dev-aws-login | 2 +- bin/dev-clean-branches | 10 +++++----- bin/dev-clone | 6 +++--- bin/dev-tofu | 2 +- bin/dev-unlock-server | 2 +- bin/dev-update-aws-config | 2 +- bin/dev-wipeenv | 2 +- 9 files changed, 19 insertions(+), 19 deletions(-) diff --git a/bin/dev b/bin/dev index ea6121a..16a2f69 100755 --- a/bin/dev +++ b/bin/dev @@ -21,7 +21,7 @@ usage() { echo echo "Commands:" for script in "$BINDIR"/dev-*; do - [[ -x $script ]] || continue + [ -x "$script" ] || continue printf " %-18s %s\n" "${script##*/dev-}" "$(doc_block "$script" | head -n 1)" done echo @@ -39,7 +39,7 @@ command_help() { local name="$1" local script="$BINDIR/dev-$name" - if [[ ! -x $script ]]; then + if [ ! -x "$script" ]; then die_unknown "$name" fi @@ -54,7 +54,7 @@ case "$SUBCOMMAND" in exit 0 ;; help) - if [[ -n ${2:-} ]]; then + if [ -n "${2:-}" ]; then command_help "$2" else usage @@ -66,7 +66,7 @@ esac shift COMMAND="$BINDIR/dev-$SUBCOMMAND" -if [[ ! -x $COMMAND ]]; then +if [ ! -x "$COMMAND" ]; then die_unknown "$SUBCOMMAND" fi diff --git a/bin/dev-archive-repo b/bin/dev-archive-repo index 3c0dfd6..5e5d7a7 100755 --- a/bin/dev-archive-repo +++ b/bin/dev-archive-repo @@ -10,14 +10,14 @@ IFS=$'\n\t' # Mirrors every branch and tag to the archive server, then archives the repo on GitHub, which # makes it read-only. A repo name given without an org is assumed to be under developersociety. -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi DEFAULT_ORG="developersociety" ARCHIVE_HOST="smirkenorff.devsoc.org" -if [ $# != 1 ]; then +if [ "$#" -ne 1 ]; then echo "Usage: dev archive-repo [org/]repo" exit 1 fi diff --git a/bin/dev-aws-login b/bin/dev-aws-login index bc45a25..e050a1b 100755 --- a/bin/dev-aws-login +++ b/bin/dev-aws-login @@ -9,7 +9,7 @@ IFS=$'\n\t' # # Defaults to the profile in $AWS_VAULT_PROFILE, or "devsoc". -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi diff --git a/bin/dev-clean-branches b/bin/dev-clean-branches index f49bd40..8c50a50 100755 --- a/bin/dev-clean-branches +++ b/bin/dev-clean-branches @@ -11,20 +11,20 @@ IFS=$'\n\t' # are found too, which "git branch --merged" cannot do on its own. main, master, dev and the # repo's own default branch are never deleted. -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi PROTECTED_BRANCHES="^main$|^master$|^dev$" ASSUME_YES=0 -if [[ ${1:-} == "-y" || ${1:-} == "--yes" ]]; then +if [ "${1:-}" = "-y" ] || [ "${1:-}" = "--yes" ]; then ASSUME_YES=1 fi # If the remote repo was added without the usual clone, then HEAD might be missing. A quick fix # can restore HEAD to the expected branch. -if [[ ! -f .git/refs/remotes/origin/HEAD ]]; then +if [ ! -f .git/refs/remotes/origin/HEAD ]; then git remote set-head origin --auto >/dev/null fi @@ -57,13 +57,13 @@ for BRANCH in $(git branch --format "%(refname:short)"); do fi done -if [[ ${#BRANCHES[@]} -gt 0 ]]; then +if [ "${#BRANCHES[@]}" -gt 0 ]; then echo "Will remove the following branches:" echo printf '%s\n' "${BRANCHES[@]}" echo - if [[ $ASSUME_YES != 1 ]]; then + if [ "$ASSUME_YES" -ne 1 ]; then echo "Press Enter to delete the above branches, or -c to bail" read -r fi diff --git a/bin/dev-clone b/bin/dev-clone index c649035..c6c5c5f 100755 --- a/bin/dev-clone +++ b/bin/dev-clone @@ -14,19 +14,19 @@ IFS=$'\n\t' # --vscode also writes a .code-workspace file pointing at the project's interpreter, and hides it # from git. -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi DEFAULT_ORG="developersociety" MAKE_VSCODE_WORKSPACE=0 -if [[ ${1:-} == "--vscode" ]]; then +if [ "${1:-}" = "--vscode" ]; then MAKE_VSCODE_WORKSPACE=1 shift fi -if [ $# != 1 ]; then +if [ "$#" -ne 1 ]; then echo "Usage: dev clone [--vscode] [org/]repo" exit 1 fi diff --git a/bin/dev-tofu b/bin/dev-tofu index 0aa6306..49cf73d 100755 --- a/bin/dev-tofu +++ b/bin/dev-tofu @@ -18,7 +18,7 @@ IFS=$'\n\t' # Set $AWS_VAULT_PROFILE to use a profile other than devsoc-tofu. Use "tofu -help" for tofu's own # help, as "--help" is handled here. -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi diff --git a/bin/dev-unlock-server b/bin/dev-unlock-server index 43b6c5c..3cc800c 100755 --- a/bin/dev-unlock-server +++ b/bin/dev-unlock-server @@ -11,7 +11,7 @@ IFS=$'\n\t' # waits for the machine to finish booting before moving on to the next one. Set # $DEV_UNLOCK_TIMEOUT to wait longer than the default 180 seconds for a slow server. -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi diff --git a/bin/dev-update-aws-config b/bin/dev-update-aws-config index 0271a7b..70f7587 100755 --- a/bin/dev-update-aws-config +++ b/bin/dev-update-aws-config @@ -10,7 +10,7 @@ IFS=$'\n\t' # Shows a diff and asks before replacing anything. The username defaults to $USER, and the last # 5 backups are kept alongside the config. -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi diff --git a/bin/dev-wipeenv b/bin/dev-wipeenv index cc540fc..09e68d4 100755 --- a/bin/dev-wipeenv +++ b/bin/dev-wipeenv @@ -9,7 +9,7 @@ IFS=$'\n\t' # # Lists what it is about to remove and asks first. pip, setuptools and wheel are left alone. -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi From 5b4fbc51abc411e10d259d2f08d4a19705d945ad Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:43 +0100 Subject: [PATCH 17/32] match repo and branch names with case instead of regex --- bin/dev-archive-repo | 10 +++++----- bin/dev-clean-branches | 14 +++++++------- bin/dev-clone | 9 ++++----- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/bin/dev-archive-repo b/bin/dev-archive-repo index 5e5d7a7..a7145b1 100755 --- a/bin/dev-archive-repo +++ b/bin/dev-archive-repo @@ -23,11 +23,11 @@ if [ "$#" -ne 1 ]; then fi # Handle org/repo, and repo -if [[ $1 == *"/"* ]]; then - REPO_NAME="$1" -else - REPO_NAME="$DEFAULT_ORG/$1" -fi +REPO_ARG="$1" +case "$REPO_ARG" in +*/*) REPO_NAME="$REPO_ARG" ;; +*) REPO_NAME="$DEFAULT_ORG/$REPO_ARG" ;; +esac PROJECT_NAME="${REPO_NAME##*/}" echo "I'm going to mirror: $REPO_NAME" diff --git a/bin/dev-clean-branches b/bin/dev-clean-branches index 8c50a50..b6c3f68 100755 --- a/bin/dev-clean-branches +++ b/bin/dev-clean-branches @@ -15,7 +15,7 @@ if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi -PROTECTED_BRANCHES="^main$|^master$|^dev$" +PROTECTED_BRANCHES="main master dev" ASSUME_YES=0 if [ "${1:-}" = "-y" ] || [ "${1:-}" = "--yes" ]; then @@ -48,9 +48,9 @@ is_squash_merged() { BRANCHES=() for BRANCH in $(git branch --format "%(refname:short)"); do - if [[ $BRANCH =~ $PROTECTED_BRANCHES ]] || [[ $BRANCH == "$DEFAULT_BRANCH" ]]; then - continue - fi + case " $PROTECTED_BRANCHES $DEFAULT_BRANCH " in + *" $BRANCH "*) continue ;; + esac if git merge-base --is-ancestor "$BRANCH" "$BASE_BRANCH" || is_squash_merged "$BRANCH"; then BRANCHES+=("$BRANCH") @@ -69,9 +69,9 @@ if [ "${#BRANCHES[@]}" -gt 0 ]; then fi # Git refuses to delete the branch you are standing on. - if [[ " ${BRANCHES[*]} " == *" $(git branch --show-current) "* ]]; then - git switch "$DEFAULT_BRANCH" - fi + case " ${BRANCHES[*]} " in + *" $(git branch --show-current) "*) git switch "$DEFAULT_BRANCH" ;; + esac # -D rather than -d, because squash-merged branches are not ancestors of the base branch and # git would refuse to delete them. is_squash_merged has already confirmed the work landed. diff --git a/bin/dev-clone b/bin/dev-clone index c6c5c5f..18a9a3b 100755 --- a/bin/dev-clone +++ b/bin/dev-clone @@ -47,11 +47,10 @@ REPO_ARG="${REPO_ARG#git@github.com:}" REPO_ARG="${REPO_ARG%/}" REPO_ARG="${REPO_ARG%.git}" -if [[ $REPO_ARG == *"/"* ]]; then - REPO_NAME="$REPO_ARG" -else - REPO_NAME="$DEFAULT_ORG/$REPO_ARG" -fi +case "$REPO_ARG" in +*/*) REPO_NAME="$REPO_ARG" ;; +*) REPO_NAME="$DEFAULT_ORG/$REPO_ARG" ;; +esac PROJECT_NAME="${REPO_NAME##*/}" GIT_URI="git@github.com:$REPO_NAME.git" From 8defa3f8f2cac4e8c969184a2ec093a742525ce0 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:43 +0100 Subject: [PATCH 18/32] time the boot wait with date instead of the SECONDS variable --- bin/dev-unlock-server | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/dev-unlock-server b/bin/dev-unlock-server index 3cc800c..6f662ca 100755 --- a/bin/dev-unlock-server +++ b/bin/dev-unlock-server @@ -48,9 +48,9 @@ wait_for_boot() { # The initramfs SSH server disappears the moment the disk unlocks, so reaching the real host's # SSH is what actually confirms the machine finished booting. local host="$1" - local deadline=$((SECONDS + BOOT_TIMEOUT_SECONDS)) + local deadline=$(($(date +%s) + BOOT_TIMEOUT_SECONDS)) - while [ $SECONDS -lt $deadline ]; do + while [ "$(date +%s)" -lt "$deadline" ]; do if ssh -o BatchMode=yes -o ConnectTimeout=5 "$host" true 2>/dev/null; then return 0 fi From bf8a8c18118a034f2e3a2d4c399f211b4c0390b2 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:43 +0100 Subject: [PATCH 19/32] explain the unfollowable source path instead of disabling SC1090 --- bin/dev-clone | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/dev-clone b/bin/dev-clone index 18a9a3b..154e302 100755 --- a/bin/dev-clone +++ b/bin/dev-clone @@ -37,7 +37,7 @@ if [ -z "${PROJECT_HOME:-}" ] || [ -z "${VIRTUALENVWRAPPER_SCRIPT:-}" ]; then exit 1 fi -# shellcheck disable=SC1090 +# shellcheck source=/dev/null source "$VIRTUALENVWRAPPER_SCRIPT" # Accept anything you might have in your clipboard: repo, org/repo, or a URL from the browser. From 08b37501588b195e00544026477e6c6aa2311750 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:43 +0100 Subject: [PATCH 20/32] prompt with read -p instead of a separate echo --- bin/dev-archive-repo | 3 +-- bin/dev-clean-branches | 3 +-- bin/dev-clone | 3 +-- bin/dev-update-aws-config | 3 +-- bin/dev-wipeenv | 3 +-- 5 files changed, 5 insertions(+), 10 deletions(-) diff --git a/bin/dev-archive-repo b/bin/dev-archive-repo index a7145b1..cb92ab9 100755 --- a/bin/dev-archive-repo +++ b/bin/dev-archive-repo @@ -34,8 +34,7 @@ echo "I'm going to mirror: $REPO_NAME" echo "To the archive server: $ARCHIVE_HOST" echo "And then archive it on GitHub, which makes it read-only." echo -echo "Press Enter to continue, or -c to bail" -read -r +read -r -p "Press Enter to continue, or -c to bail" TMPDIR=$(mktemp -d) trap 'rm -rf "$TMPDIR"' EXIT diff --git a/bin/dev-clean-branches b/bin/dev-clean-branches index b6c3f68..53f6a68 100755 --- a/bin/dev-clean-branches +++ b/bin/dev-clean-branches @@ -64,8 +64,7 @@ if [ "${#BRANCHES[@]}" -gt 0 ]; then echo if [ "$ASSUME_YES" -ne 1 ]; then - echo "Press Enter to delete the above branches, or -c to bail" - read -r + read -r -p "Press Enter to delete the above branches, or -c to bail" fi # Git refuses to delete the branch you are standing on. diff --git a/bin/dev-clone b/bin/dev-clone index 154e302..a5cd711 100755 --- a/bin/dev-clone +++ b/bin/dev-clone @@ -107,8 +107,7 @@ echo "I'm going to clone: $GIT_URI" echo "Into this directory: $PROJECT_DIR" echo "And setup virtualenvwrapper for you." echo -echo "Press Enter to continue..." -read -r +read -r -p "Press Enter to continue..." git clone "$GIT_URI" "$PROJECT_DIR" cd "$PROJECT_DIR" diff --git a/bin/dev-update-aws-config b/bin/dev-update-aws-config index 70f7587..a06577a 100755 --- a/bin/dev-update-aws-config +++ b/bin/dev-update-aws-config @@ -41,8 +41,7 @@ if [ -f "$CONFIG_FILE" ]; then fi echo - echo "Press Enter to apply the above changes for '$CONFIG_USERNAME', or -c to bail" - read -r + read -r -p "Press Enter to apply the above changes for '$CONFIG_USERNAME', or -c to bail" TIMESTAMP=$(date -u +"%Y%m%dT%H%M%SZ") cp "$CONFIG_FILE" "$CONFIG_FILE.old.$TIMESTAMP" diff --git a/bin/dev-wipeenv b/bin/dev-wipeenv index 09e68d4..9f2e098 100755 --- a/bin/dev-wipeenv +++ b/bin/dev-wipeenv @@ -34,7 +34,6 @@ echo "Will uninstall the following from $VIRTUAL_ENV:" echo echo "$PACKAGES" echo -echo "Press Enter to uninstall the above packages, or -c to bail" -read -r +read -r -p "Press Enter to uninstall the above packages, or -c to bail" echo "$PACKAGES" | xargs pip uninstall -y From 7f8f07ccaa9737cb25e106f5efb4bae01aed3862 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:43 +0100 Subject: [PATCH 21/32] stop clobbering TMPDIR when mirroring a repo --- bin/dev-archive-repo | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/bin/dev-archive-repo b/bin/dev-archive-repo index cb92ab9..a5a930e 100755 --- a/bin/dev-archive-repo +++ b/bin/dev-archive-repo @@ -36,10 +36,12 @@ echo "And then archive it on GitHub, which makes it read-only." echo read -r -p "Press Enter to continue, or -c to bail" -TMPDIR=$(mktemp -d) -trap 'rm -rf "$TMPDIR"' EXIT +# Not $TMPDIR - that is the standard var mktemp and git read, and clobbering it would move +# everyone else's temporary files in here too. +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT -CLONE_DIR="$TMPDIR/$PROJECT_NAME.git" +CLONE_DIR="$WORK_DIR/$PROJECT_NAME.git" git clone --bare "git@github.com:$REPO_NAME.git" "$CLONE_DIR" git -C "$CLONE_DIR" push --mirror "git@$ARCHIVE_HOST:archive/$PROJECT_NAME.git" From 88440b5c3a0142247869219a88993db975135350 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:43 +0100 Subject: [PATCH 22/32] run tofu through tofu_exec in the passthrough case too --- bin/dev-tofu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/dev-tofu b/bin/dev-tofu index 49cf73d..62fa8c2 100755 --- a/bin/dev-tofu +++ b/bin/dev-tofu @@ -130,6 +130,6 @@ all) ;; *) ensure_initialised - exec aws-vault exec "$PROFILE" -- tofu "$@" + tofu_exec "$@" ;; esac From d4c4a52ceeba5cf0d2992caf289efcb5db3e352d Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:44 +0100 Subject: [PATCH 23/32] delete old aws config backups with xargs --- bin/dev-update-aws-config | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bin/dev-update-aws-config b/bin/dev-update-aws-config index a06577a..6fb3fcc 100755 --- a/bin/dev-update-aws-config +++ b/bin/dev-update-aws-config @@ -53,8 +53,6 @@ mv "$TMPFILE" "$CONFIG_FILE" # Backups otherwise accumulate forever, one per run. { ls -1t "$CONFIG_FILE".old.* 2>/dev/null || true; } | tail -n +$((BACKUPS_TO_KEEP + 1)) | - while read -r OLD_BACKUP; do - rm -f "$OLD_BACKUP" - done + xargs rm -f echo "Config file updated!" From 9ea765d3b74a452b0dfb4df636469976842ebe95 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:52 +0100 Subject: [PATCH 24/32] assert on substrings with an expect_contains helper --- tests/helpers.sh | 11 +++++++++++ tests/test-clean-branches.sh | 5 ++--- tests/test-dev.sh | 25 ++++++++++--------------- tests/test-unlock-server.sh | 5 ++--- 4 files changed, 25 insertions(+), 21 deletions(-) diff --git a/tests/helpers.sh b/tests/helpers.sh index 708b2fa..796b2ce 100644 --- a/tests/helpers.sh +++ b/tests/helpers.sh @@ -31,6 +31,17 @@ expect() { fi } +# Checks for a substring, which is what most of the output assertions here need: the tests care +# that a message appeared, not that the whole output matched. +expect_contains() { + local description="$1" haystack="$2" needle="$3" + + case "$haystack" in + *"$needle"*) ;; + *) fail "$description, got: $haystack" ;; + esac +} + fail() { echo "FAIL: $1" FAILED=1 diff --git a/tests/test-clean-branches.sh b/tests/test-clean-branches.sh index 3333dec..caeaaeb 100755 --- a/tests/test-clean-branches.sh +++ b/tests/test-clean-branches.sh @@ -57,8 +57,7 @@ git switch --quiet main git branch --quiet -D unmerged-branch SECOND_RUN=$("$CLEAN_BRANCHES" --yes) -if [[ $SECOND_RUN != *"No local branches need removing"* ]]; then - fail "expected a clean repo to report nothing to remove, got: $SECOND_RUN" -fi +expect_contains "expected a clean repo to report nothing to remove" \ + "$SECOND_RUN" "No local branches need removing" finish "merged and squash-merged branches removed, and a clean repo says so" diff --git a/tests/test-dev.sh b/tests/test-dev.sh index 2b85051..5155332 100755 --- a/tests/test-dev.sh +++ b/tests/test-dev.sh @@ -33,26 +33,23 @@ chmod +x "$BINDIR/dev-madeupcommand" expect "arguments are passed through untouched" \ "got: --flag one two" "$("$BINDIR/dev" madeupcommand --flag one two)" -if [[ $("$BINDIR/dev" help) != *"madeupcommand"* ]]; then - fail "a newly added command should appear in 'dev help' without being registered" -fi +expect_contains "a newly added command should appear in 'dev help' without being registered" \ + "$("$BINDIR/dev" help)" "madeupcommand" expect "commands are also runnable directly, without the dispatcher" \ "got: direct" "$("$BINDIR/dev-madeupcommand" direct)" for INVOCATION in "" "-h" "--help" "help"; do - if [[ $("$BINDIR/dev" ${INVOCATION:+"$INVOCATION"}) != *"Usage: dev "* ]]; then - fail "'dev ${INVOCATION}' should print the usage summary" - fi + expect_contains "'dev ${INVOCATION}' should print the usage summary" \ + "$("$BINDIR/dev" ${INVOCATION:+"$INVOCATION"})" "Usage: dev " done if "$BINDIR/dev" no-such-command >/dev/null 2>&1; then fail "an unknown command should exit non-zero" fi -if [[ $("$BINDIR/dev" no-such-command 2>&1 || true) != *"Unknown command: no-such-command"* ]]; then - fail "an unknown command should say which one it didn't recognise" -fi +expect_contains "an unknown command should say which one it didn't recognise" \ + "$("$BINDIR/dev" no-such-command 2>&1 || true)" "Unknown command: no-such-command" if "$BINDIR/dev" help no-such-command >/dev/null 2>&1; then fail "'dev help' for an unknown command should exit non-zero" @@ -70,15 +67,13 @@ for SCRIPT_PATH in "$SOURCE_BINDIR"/dev-*; do NAME="${SCRIPT_PATH##*/dev-}" HELP_OUTPUT=$("$SOURCE_BINDIR/dev" help "$NAME") - if [[ $HELP_OUTPUT != *"dev $NAME"* ]]; then - fail "'dev help $NAME' doesn't document a 'dev $NAME' usage line" - fi + expect_contains "'dev help $NAME' doesn't document a 'dev $NAME' usage line" \ + "$HELP_OUTPUT" "dev $NAME" expect "'$NAME --help' matches 'dev help $NAME'" "$HELP_OUTPUT" "$("$SCRIPT_PATH" --help)" - if [[ $("$SOURCE_BINDIR/dev" help) != *" $NAME "* ]]; then - fail "'$NAME' is missing from the 'dev help' summary list" - fi + expect_contains "'$NAME' is missing from the 'dev help' summary list" \ + "$("$SOURCE_BINDIR/dev" help)" " $NAME " done finish "subcommands are discovered, dispatched, and all document themselves" diff --git a/tests/test-unlock-server.sh b/tests/test-unlock-server.sh index 2614da9..ce2d0b2 100755 --- a/tests/test-unlock-server.sh +++ b/tests/test-unlock-server.sh @@ -71,8 +71,7 @@ expect "each host is unlocked as root and then checked for boot, in order" \ OUTPUT=$(DEV_UNLOCK_TIMEOUT=1 STUB_UP_HOSTS="" \ "$BINDIR/dev" unlock-server slow.example 2>&1 >/dev/null) -if [[ $OUTPUT != *"did not come back"* ]]; then - fail "a host which never boots should warn on stderr, got: $OUTPUT" -fi +expect_contains "a host which never boots should warn on stderr" \ + "$OUTPUT" "did not come back" finish "passphrases fetched per host, unlocked in order, and slow servers warn" From 93902930286d712c71afeaa2f5d8d5d5063309a6 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:52 +0100 Subject: [PATCH 25/32] inline the utility targets into the targets that use them --- Makefile | 47 +++++++++++------------------------------------ 1 file changed, 11 insertions(+), 36 deletions(-) diff --git a/Makefile b/Makefile index a6b0c28..cd331bd 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,8 @@ SHELL=/bin/bash .DEFAULT_GOAL := help +SHELL_SOURCES = bin/dev* tests/*.sh + # ------------------------------- # Common targets for Dev projects @@ -12,55 +14,28 @@ SHELL=/bin/bash # the current project, then keep the target and simply make it do nothing. help: ## This help dialog. -help: help-display +help: + @awk '/^[\-[:alnum:]]*: ##/ { split($$0, x, "##"); printf "%20s%s\n", x[1], x[2]; }' $(MAKEFILE_LIST) install-local: ## Install the tools needed to work on this project. -install-local: brew-install-local +install-local: + brew install shellcheck shfmt check: ## Check for any obvious errors in the project's setup. check: lint test format: ## Run this project's code formatters. -format: shell-format +format: + shfmt --indent 4 --write $(SHELL_SOURCES) lint: ## Lint the project. -lint: shell-lint shell-format-check - -test: ## Run this project's tests. -test: shell-test - - -# --------------- -# Utility targets -# --------------- -# -# Targets which are used by the common targets. You likely want to customise these per project, -# to ensure they're pointing at the correct directories, etc. - -# Installs -brew-install-local: - brew install shellcheck shfmt - - -# Shell -SHELL_SOURCES = bin/dev* tests/*.sh - -shell-lint: +lint: shellcheck $(SHELL_SOURCES) - -shell-format: - shfmt --indent 4 --write $(SHELL_SOURCES) - -shell-format-check: shfmt --indent 4 --diff $(SHELL_SOURCES) -shell-test: +test: ## Run this project's tests. +test: @for test in tests/test-*.sh; do \ echo "== $$test"; \ "$$test" || exit 1; \ done - - -# Help -help-display: - @awk '/^[\-[:alnum:]]*: ##/ { split($$0, x, "##"); printf "%20s%s\n", x[1], x[2]; }' $(MAKEFILE_LIST) From 63661c8a779df22f23d975352535cc3e8096703c Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:52 +0100 Subject: [PATCH 26/32] install shfmt in ci so the format check can run --- .github/workflows/test.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 36660e8..e8af333 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -9,4 +9,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - name: Install shfmt + run: | + go install mvdan.cc/sh/v3/cmd/shfmt@v3.14.1 + echo "$HOME/go/bin" >> "$GITHUB_PATH" - run: make check From afda3e3d259fb3dc485ec91d1bfd5b1a48150134 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:52 +0100 Subject: [PATCH 27/32] drop the awscli dependency from the formula --- Formula/devtools.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/Formula/devtools.rb b/Formula/devtools.rb index 956a794..bcb0250 100644 --- a/Formula/devtools.rb +++ b/Formula/devtools.rb @@ -16,7 +16,6 @@ class Devtools < Formula version "1.0.0" depends_on "aws-vault" - depends_on "awscli" depends_on "gh" depends_on "jq" depends_on "opentofu" From 6d1a9cda14d04e708669796992a5fa0a183bb605 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:53 +0100 Subject: [PATCH 28/32] move the tap notes above the formula class --- Formula/devtools.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Formula/devtools.rb b/Formula/devtools.rb index bcb0250..cf90962 100644 --- a/Formula/devtools.rb +++ b/Formula/devtools.rb @@ -1,11 +1,11 @@ +# The tap and the tools are the same repo, so the scripts are already on disk next to this +# formula: Homebrew builds from the tap's own checkout rather than fetching from GitHub again. +# That also makes testing a branch a matter of checking it out in the tap, with no push needed. + class Devtools < Formula desc "Development tools for The Developer Society" homepage "https://github.com/developersociety/tools" - # The tap and the tools are the same repo, so the scripts are already on disk next to this - # formula: Homebrew builds from the tap's own checkout rather than fetching from GitHub again. - # That also makes testing a branch a matter of checking it out in the tap, with no push needed. - # # A pinned revision would need a second commit after every tag, so the version is what Homebrew # keys its cache on: bump it to ship a release. While testing a branch, "brew fetch --force # devtools" clears the cached clone without a bump. From b53c98c3af936de884555f1334b4c2498bb3cdd4 Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:53 +0100 Subject: [PATCH 29/32] add AGENTS.md with the shell house style --- AGENTS.md | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..76dcb23 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,144 @@ +# AGENTS.md + +Notes for anyone — human or agent — working on this repo. The README covers installing and using the tools, `docs/` +covers the contributor workflow, and this covers writing the code. + +## What this repo is + +A Homebrew tap and the tools it installs, in one repo. `bin/dev` is a dispatcher: it finds its subcommands by globbing +for sibling `bin/dev-*` scripts, so adding a file is all it takes to add a command. There is no registry, no list of +commands, and no separate usage text to keep in step. + +``` +bin/dev dispatcher: discovery, help, dispatch +bin/dev-* one executable per command +tests/helpers.sh shared assertions and stub scaffolding +tests/test-*.sh one test script per commandÎ +Formula/devtools.rb the Homebrew formula, which builds from this same checkout +Makefile format, lint, test — the entry point for all of it +``` + +## Shell + +Everything is bash: `#!/usr/bin/env bash` on every script, `# shellcheck shell=bash` on the sourced-only +`tests/helpers.sh`. Nothing uses a bash 4 feature, so the scripts run on the bash 3.2 that ships with macOS as well as +on a Homebrew bash. Keep it that way — no `mapfile`, no +`${var^^}`, no `declare -A`, no `<<<`, no process substitution. + +Within bash, prefer the plain POSIX construct. The goal is that a reader who knows `sh` can follow any script here +without knowing bash's shorthand. + +- **`[ ]`, not `[[ ]]`.** Quote every variable inside it: `[ "$#" -ne 1 ]`, `[ -x "$script" ]`, + `[ -n "${2:-}" ]`. Use the numeric operators (`-ne`, `-lt`, `-gt`) for numbers and `=` / `!=` + for strings. +- **`case` only for patterns.** A glob or an alternation list is what `case` is for: + ```bash + case "$REPO_ARG" in + */*) REPO_NAME="$REPO_ARG" ;; + *) REPO_NAME="$DEFAULT_ORG/$REPO_ARG" ;; + esac + ``` + For an exact match against one or two values, `if [ ... ] || [ ... ]` is shorter and reads better. Don't reach for + `case` just to avoid repeating `"${1:-}"`. +- **No regex.** `=~` is bash-only and needs a second language in your head. A membership test is a space-wrapped + `case` — the wrapping spaces are what make it an exact-word match, so `mainline` + doesn't match `main`: + ```bash + case " $PROTECTED_BRANCHES $DEFAULT_BRANCH " in + *" $BRANCH "*) continue ;; + esac + ``` +- **No `$SECONDS`, `$RANDOM` or other bash magic variables.** A deadline is + `$(($(date +%s) + $TIMEOUT))`. +- **Words over punctuation.** `source` rather than `.`, because a lone dot is easy to miss. The scripts are bash, so + there is nothing to gain by spelling it the POSIX way. +- **Keep what earns its place.** Arrays, `local`, and `set -o pipefail` are bash-only and stay: + rewriting them in POSIX makes the scripts longer and less safe, which defeats the point. + +Deliberately unfollowable `source` lines get a directive with a reason, not a rule number — +`# shellcheck source=/dev/null # path is set per-machine` rather than +`# shellcheck disable=SC1090`. + +## Style + +The house style is "least sugar, most explicit". Someone reading a script a year from now should not have to look +anything up. + +- 100 character lines. Four-space indent, enforced by `shfmt --indent 4`. +- Every script opens with `set -euo pipefail` and `IFS=$'\n\t'`. +- Hard-coded values are named constants in `UPPER_CASE`, declared near the top of the file, above the logic that uses + them. This holds during refactors too: if the mechanism consuming a constant changes, reshape the constant's value to + suit — don't inline it and delete the name. +- Name your arguments. `REPO_ARG="$1"` once, then use the name, rather than `$1` scattered about. +- Prompt on the `read` that waits for it: `read -r -p "Press Enter to continue, or -c to + bail"`, not an `echo` followed by a bare `read -r` that silently fills `$REPLY`. +- Descriptive names, and never a magic environment variable as a scratch variable. `WORK_DIR`, not + `TMPDIR` — that one is read by `mktemp` and `git`, so assigning it moves everyone else's temporary files too. +- Comments explain *why*. The `# help:` block explains *what*, and it is the only user-facing documentation of a + command. +- Anything creating a temporary directory cleans it up: `trap 'rm -rf "$WORK_DIR"' EXIT`. +- Anything destructive shows what it is about to do and waits for Enter first. + +## Adding a command + +1. Create `bin/dev-something`, `chmod +x`, with the standard header. +2. Give it a `# help:` block. The first line is the one-line summary in `dev help`; the whole block is what + `dev help something` and `dev something --help` print. +3. Wire up `--help` with the standard guard, which re-enters the dispatcher rather than printing anything itself: + ```bash + if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" + fi + ``` +4. Write `tests/test-something.sh`. +5. Add a row to the table in `README.md`. + +Homebrew installs everything matching `bin/dev*` and `dev help` globs for it, so there is nothing else to register. + +## Tests + +Plain bash scripts, no framework. One `tests/test-.sh` per command, executable, run by +`make test`, which loops over `tests/test-*.sh` and stops at the first script to exit non-zero. Run one directly while +working on it: `./tests/test-clone.sh`. + +Every test sources `tests/helpers.sh`, which provides: + +- `make_workdir` — `mktemp -d` into `$WORKDIR` with an `EXIT` trap, and puts `$WORKDIR/stub` at the front of `$PATH`. +- `write_stub ` — writes an executable stub from stdin into the stub directory. +- `expect ` — exact-match assertion. +- `expect_contains ` — substring assertion, which is what most output checks want. +- `fail ` — records a failure and carries on. +- `finish ` — exits non-zero if anything failed, otherwise prints `PASS: `. + +Assertions report and continue rather than aborting, so one run tells you everything that is broken instead of only the +first thing. That is why `finish` is what decides the exit status, and why every test must end with a `finish` line. + +The commands here talk to git, ssh, pip, aws-vault, pyenv, `gh` and the 1Password CLI. Tests stub all of them with +`write_stub`, so they need no credentials, touch no real repos or servers, and write nothing outside their temporary +directory. A stub usually logs its arguments to a file the test then asserts against: + +```bash +write_stub git <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +echo "$*" >> "$STUB_GIT_LOG" +STUB + +export STUB_GIT_LOG="$WORKDIR/git.log" +``` + +Test the behaviour worth protecting — which arguments the command builds, which paths it writes, what it refuses to do, +and that it cleans up after a failure — rather than restating the implementation. Each test opens with a comment saying +what is worth checking in that command and why. Commands that wait for Enter are driven with `printf '\n' | ...`. + +## Checks + +`make check` — shellcheck, `shfmt --diff`, then the tests — is exactly what CI runs, so a green +`make check` locally means a green build. `make format` fixes the formatting it complains about. CI installs shfmt with +`go install`, because the GitHub runner image ships shellcheck but not shfmt. + +## Docs + +`docs/development.md` covers the contributor workflow: tooling, testing a branch through the Homebrew tap, and +releasing. `docs/tofu-env.md` explains the `dev tofu env` workflow. The README is deliberately limited to installation +and usage — new documentation goes in `docs/`. From cde427df0fbcf11e59de78a4f31da18ba506ba7c Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 10:28:53 +0100 Subject: [PATCH 30/32] move the contributor docs out of the readme --- README.md | 143 +++++++++----------------------------------- docs/development.md | 75 +++++++++++++++++++++++ docs/tofu-env.md | 23 +++++++ 3 files changed, 125 insertions(+), 116 deletions(-) create mode 100644 docs/development.md create mode 100644 docs/tofu-env.md diff --git a/README.md b/README.md index fae6c48..243e40c 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,11 @@ # The Developer Society — Development Tools -Tools for making development at The Developer Society quicker, easier and less error prone. - - +Tools for making development at The Developer Society quicker, easier and less error-prone. ## Installation -The tools are distributed through our own Homebrew tap. The repo is private, so Homebrew fetches -it over SSH using the GitHub key you already have set up: +The tools are distributed through our own Homebrew tap. The repo is private, so Homebrew fetches it over SSH using the +GitHub key you already have set up: ```console $ brew tap developersociety/tools git@github.com:developersociety/tools.git @@ -16,12 +14,11 @@ $ brew install devtools ``` The explicit git URL is required: without it Homebrew guesses a public -`https://github.com/developersociety/homebrew-tools` and gets a 404. `brew trust` is required -too, as Homebrew refuses to load formulae from third-party taps until you say so. +`https://github.com/developersociety/homebrew-tools` and gets a 404. `brew trust` is required too, as Homebrew refuses +to load formulae from third-party taps until you say so. -If you previously added a checkout of this repo to your `$PATH`, remove that from your shell -profile. It shadows the Homebrew copies, and you'll keep running the old scripts without -noticing — `brew install` warns about this, but the warning is easy to scroll past. +If you previously added a checkout of this repo to your `$PATH`, remove that from your shell profile. It shadows the +Homebrew copies, and you'll keep running the old scripts without noticing. To upgrade later: @@ -29,13 +26,10 @@ To upgrade later: $ brew upgrade devtools ``` -Every tool is also available as its own command, so `dev clone devsoc` and `dev-clone devsoc` do -the same thing. - ## Usage -Run `dev help` for the list of commands, and `dev help ` for the detail on one of them. -Each command also takes `--help` directly: +Run `dev help` for the list of commands, and `dev help ` for the detail on one of them. Each command also takes +`--help` directly, and is available under its own name, so `dev clone devsoc` and `dev-clone devsoc` do the same thing. ```console $ dev help @@ -43,110 +37,27 @@ $ dev help tofu $ dev tofu --help ``` -Each command explains itself, so the list below is a map rather than a manual — run -`dev help ` for the detail. - -| Command | What it does | -| --- | --- | -| `dev clone` | Clone a repo and set up virtualenvwrapper for it | -| `dev clean-branches` | Delete merged local branches, squash-merges included, and prune remotes | -| `dev tofu` | Run tofu with the devsoc-tofu profile, and manage project env vars | -| `dev aws-login` | Open the AWS console via aws-vault | -| `dev update-aws-config` | Rewrite `~/.aws/config` from the 1Password template | -| `dev unlock-server` | Unlock the encrypted root filesystem on one or more servers | -| `dev archive-repo` | Mirror a repo to the archive server, then archive it on GitHub | -| `dev wipeenv` | Uninstall every package in the active virtualenv | - -### dev tofu env - -The one command worth explaining outside its own help, because the workflow behind it isn't -obvious. A project's environment variables live in the tofu state as `random_password` resources -declared in the project's `envvars.tf`. Reading and setting them used to mean copy-pasting raw -`tofu show -json | jq ...` and `state rm` / `import` incantations from the comments at the top of -each `envvars.tf`: +Each command explains itself, so the list below is a map rather than a manual. -```console -$ dev tofu env # list every variable and its value -$ dev tofu env SENTRY_AUTH_TOKEN # print one value -$ dev tofu env set SENTRY_AUTH_TOKEN # prompt for the value, then import it -``` +| Command | What it does | +|-------------------------|-------------------------------------------------------------------------| +| `dev clone` | Clone a repo and set up virtualenvwrapper for it | +| `dev clean-branches` | Delete merged local branches, squash-merges included, and prune remotes | +| `dev tofu` | Run tofu with the devsoc-tofu profile, and manage project env vars | +| `dev aws-login` | Open the AWS console via aws-vault | +| `dev update-aws-config` | Rewrite `~/.aws/config` from the 1Password template | +| `dev unlock-server` | Unlock the encrypted root filesystem on one or more servers | +| `dev archive-repo` | Mirror a repo to the archive server, then archive it on GitHub | +| `dev wipeenv` | Uninstall every package in the active virtualenv | -Setting a variable removes it from the state and re-imports it, so a `dev tofu apply` is still -needed to get the new value onto the running service. The variable has to have a -`random_password` resource in `envvars.tf` before it can be imported, and variables are told -apart from tofu's internal passwords by their upper case names. +Managing a project's environment variables has a workflow of its own — see +[docs/tofu-env.md](docs/tofu-env.md). ## Development -Please contribute! If you find yourself needing to do the same thing over and over, or you keep -forgetting a process, or you just feel you're typing too much to do boring stuff... then create a -script to automate/help/optimise it. And then we can all benefit. - -New tools go in `bin/` named `dev-something`, with a `# help: one line summary` comment near the -top. `dev help` picks them up automatically, and Homebrew installs anything matching `bin/dev*`, -so there's no list to keep in sync. - -New commands are documented in the comment block starting at their `# help:` line. `dev help` -prints the first line in its summary list, `dev help ` prints the whole block, and each -script's `--help` prints the same thing, so there's only ever one copy of the usage text. - -The tools needed to work on this repo are shellcheck and shfmt. There's no virtualenv, because -there's no Python here: - -```console -$ make install-local -$ make format -$ make check -``` - -`make check` runs shellcheck, checks the formatting, and then runs the tests, which is what CI -runs too. `make help` lists the targets. - -### Testing locally - -For day to day work, put the checkout on your `$PATH` and run the commands straight from it: - -```console -$ export PATH="$PWD/bin:$PATH" -$ dev help -``` - -To test the Homebrew formula itself, tap the repo and check out the branch you want in the tap's -own clone. The formula builds from that clone, so whatever branch it's on is what gets installed -— nothing needs pushing to GitHub, and the formula needs no editing: - -```console -$ brew tap developersociety/tools git@github.com:developersociety/tools.git -$ brew trust developersociety/tools - -$ git -C "$(brew --repo developersociety/tools)" switch some-branch -$ brew fetch --force devtools -$ brew install devtools -$ brew test devtools -$ dev help -``` - -Then switch the tap clone back to `master` when you're done. - -Two things to know. Homebrew clones committed state, so commit before installing — staged and -unstaged work is invisible to it, and a missing file shows up as a mysteriously incomplete -install rather than an error. And it caches the clone against the formula's `version`, so -`brew fetch --force devtools` is needed between installs of the same version. - -To remove it again: - -```console -$ brew uninstall devtools -$ brew untap developersociety/tools -``` - -Note that `brew uninstall` also sweeps up orphaned dependencies, so check what it reports before -walking away from it. - -Every command has a test in `tests/`. They stub out git, ssh, pip, aws-vault, pyenv and the -1Password CLI, so they need no credentials and touch nothing outside a temporary directory. - -### Releasing +Please contribute! If you find yourself needing to do the same thing over and over, or you keep forgetting a process, or +you just feel you're typing too much to do boring stuff ... then create a script to automate/help/optimise it. And then +we can all benefit. -Homebrew keys its cache on the `version` in `Formula/devtools.rb`, so shipping a release means -bumping that one line and pushing to `master`. Everyone picks it up on their next `brew upgrade`. +See [docs/development.md](docs/development.md) to get set up, and [AGENTS.md](AGENTS.md) for the house style and how the +tests are put together. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..aa51e30 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,75 @@ +# Development + +How to work on the tools themselves. For the house style, the shell conventions and how the tests +are put together, see [AGENTS.md](../AGENTS.md). + +## Adding a tool + +New tools go in `bin/` named `dev-something`, with a `# help: one line summary` comment near the +top. `dev help` picks them up automatically, and Homebrew installs anything matching `bin/dev*`, +so there's no list to keep in sync. Every command has a test in `tests/`, which stubs out the +commands it calls so it needs no credentials. + +[AGENTS.md](../AGENTS.md) has the step by step: the script header, the `--help` guard, and how the +tests are put together. + +## Tooling + +The tools needed to work on this repo are shellcheck and shfmt. There's no virtualenv, because +there's no Python here: + +```console +$ make install-local +$ make format +$ make check +``` + +`make check` runs shellcheck, checks the formatting, and then runs the tests, which is what CI +runs too. `make help` lists the targets. + +## Testing locally + +For day to day work, put the checkout on your `$PATH` and run the commands straight from it: + +```console +$ export PATH="$PWD/bin:$PATH" +$ dev help +``` + +To test the Homebrew formula itself, tap the repo and check out the branch you want in the tap's +own clone. The formula builds from that clone, so whatever branch it's on is what gets installed +— nothing needs pushing to GitHub, and the formula needs no editing: + +```console +$ brew tap developersociety/tools git@github.com:developersociety/tools.git +$ brew trust developersociety/tools + +$ git -C "$(brew --repo developersociety/tools)" switch some-branch +$ brew fetch --force devtools +$ brew install devtools +$ brew test devtools +$ dev help +``` + +Then switch the tap clone back to `master` when you're done. + +Two things to know. Homebrew clones committed state, so commit before installing — staged and +unstaged work is invisible to it, and a missing file shows up as a mysteriously incomplete +install rather than an error. And it caches the clone against the formula's `version`, so +`brew fetch --force devtools` is needed between installs of the same version. + +To remove it again: + +```console +$ brew uninstall devtools +$ brew untap developersociety/tools +``` + +Note that `brew uninstall` also sweeps up orphaned dependencies, so check what it reports before +walking away from it. + +## Releasing + +The tap and the tools are the same repo, so the formula builds from its own checkout. Homebrew +keys its cache on the `version` in `Formula/devtools.rb`, so shipping a release means bumping that +one line and pushing to `master`. Everyone picks it up on their next `brew upgrade`. diff --git a/docs/tofu-env.md b/docs/tofu-env.md new file mode 100644 index 0000000..2a25027 --- /dev/null +++ b/docs/tofu-env.md @@ -0,0 +1,23 @@ +# Project environment variables + +`dev tofu env` reads and sets the environment variables for a project. The workflow behind it +isn't obvious, which is why it gets a page of its own. + +A project's environment variables live in the tofu state as `random_password` resources declared +in the project's `envvars.tf`. Reading and setting them used to mean copy-pasting raw +`tofu show -json | jq ...` and `state rm` / `import` incantations from the comments at the top of +each `envvars.tf`. Instead: + +```console +$ dev tofu env # list every variable and its value +$ dev tofu env SENTRY_AUTH_TOKEN # print one value +$ dev tofu env set SENTRY_AUTH_TOKEN # prompt for the value, then import it +``` + +Three things to know: + +- Setting a variable removes it from the state and re-imports it, so a `dev tofu apply` is still + needed to get the new value onto the running service. +- The variable has to have a `random_password` resource in `envvars.tf` before it can be + imported. +- Variables are told apart from tofu's internal passwords by their upper case names. From a3b8db8fced423981a8477ffbc3ed0dfc31cfc5f Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 13:13:51 +0100 Subject: [PATCH 31/32] removed redundant code --- AGENTS.md | 131 ++++++++++++----------------------- Formula/devtools.rb | 5 +- bin/dev-clean-branches | 11 +-- docs/development.md | 10 --- tests/test-clean-branches.sh | 4 +- 5 files changed, 51 insertions(+), 110 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 76dcb23..b2eb77f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,32 +1,20 @@ # AGENTS.md -Notes for anyone — human or agent — working on this repo. The README covers installing and using the tools, `docs/` -covers the contributor workflow, and this covers writing the code. +The rules for writing code in this repo. The README covers installing and using the tools, and +`docs/development.md` covers the contributor workflow — tooling, testing a branch and releasing. -## What this repo is - -A Homebrew tap and the tools it installs, in one repo. `bin/dev` is a dispatcher: it finds its subcommands by globbing -for sibling `bin/dev-*` scripts, so adding a file is all it takes to add a command. There is no registry, no list of -commands, and no separate usage text to keep in step. - -``` -bin/dev dispatcher: discovery, help, dispatch -bin/dev-* one executable per command -tests/helpers.sh shared assertions and stub scaffolding -tests/test-*.sh one test script per commandÎ -Formula/devtools.rb the Homebrew formula, which builds from this same checkout -Makefile format, lint, test — the entry point for all of it -``` +`bin/dev` finds its subcommands by globbing for sibling `bin/dev-*` scripts, so a new executable +with a `# help:` block is a new command. There is no registry to update. ## Shell -Everything is bash: `#!/usr/bin/env bash` on every script, `# shellcheck shell=bash` on the sourced-only -`tests/helpers.sh`. Nothing uses a bash 4 feature, so the scripts run on the bash 3.2 that ships with macOS as well as -on a Homebrew bash. Keep it that way — no `mapfile`, no +Everything is bash: `#!/usr/bin/env bash` on every script, `# shellcheck shell=bash` on the +sourced-only `tests/helpers.sh`. Nothing uses a bash 4 feature, so the scripts run on the bash 3.2 +that ships with macOS as well as on a Homebrew bash. Keep it that way — no `mapfile`, no `${var^^}`, no `declare -A`, no `<<<`, no process substitution. -Within bash, prefer the plain POSIX construct. The goal is that a reader who knows `sh` can follow any script here -without knowing bash's shorthand. +Within bash, prefer the plain POSIX construct. The goal is that a reader who knows `sh` can follow +any script here without knowing bash's shorthand. - **`[ ]`, not `[[ ]]`.** Quote every variable inside it: `[ "$#" -ne 1 ]`, `[ -x "$script" ]`, `[ -n "${2:-}" ]`. Use the numeric operators (`-ne`, `-lt`, `-gt`) for numbers and `=` / `!=` @@ -38,10 +26,10 @@ without knowing bash's shorthand. *) REPO_NAME="$DEFAULT_ORG/$REPO_ARG" ;; esac ``` - For an exact match against one or two values, `if [ ... ] || [ ... ]` is shorter and reads better. Don't reach for - `case` just to avoid repeating `"${1:-}"`. -- **No regex.** `=~` is bash-only and needs a second language in your head. A membership test is a space-wrapped - `case` — the wrapping spaces are what make it an exact-word match, so `mainline` + For an exact match against one or two values, `if [ ... ] || [ ... ]` is shorter and reads + better. Don't reach for `case` just to avoid repeating `"${1:-}"`. +- **No regex.** `=~` is bash-only and needs a second language in your head. A membership test is a + space-wrapped `case` — the wrapping spaces are what make it an exact-word match, so `mainline` doesn't match `main`: ```bash case " $PROTECTED_BRANCHES $DEFAULT_BRANCH " in @@ -50,8 +38,8 @@ without knowing bash's shorthand. ``` - **No `$SECONDS`, `$RANDOM` or other bash magic variables.** A deadline is `$(($(date +%s) + $TIMEOUT))`. -- **Words over punctuation.** `source` rather than `.`, because a lone dot is easy to miss. The scripts are bash, so - there is nothing to gain by spelling it the POSIX way. +- **Words over punctuation.** `source` rather than `.`, because a lone dot is easy to miss. The + scripts are bash, so there is nothing to gain by spelling it the POSIX way. - **Keep what earns its place.** Arrays, `local`, and `set -o pipefail` are bash-only and stay: rewriting them in POSIX makes the scripts longer and less safe, which defeats the point. @@ -61,84 +49,53 @@ Deliberately unfollowable `source` lines get a directive with a reason, not a ru ## Style -The house style is "least sugar, most explicit". Someone reading a script a year from now should not have to look -anything up. +The house style is "least sugar, most explicit". Someone reading a script a year from now should +not have to look anything up. - 100 character lines. Four-space indent, enforced by `shfmt --indent 4`. - Every script opens with `set -euo pipefail` and `IFS=$'\n\t'`. -- Hard-coded values are named constants in `UPPER_CASE`, declared near the top of the file, above the logic that uses - them. This holds during refactors too: if the mechanism consuming a constant changes, reshape the constant's value to - suit — don't inline it and delete the name. +- Hard-coded values are named constants in `UPPER_CASE`, declared near the top of the file, above + the logic that uses them. This holds during refactors too: if the mechanism consuming a constant + changes, reshape the constant's value to suit — don't inline it and delete the name. - Name your arguments. `REPO_ARG="$1"` once, then use the name, rather than `$1` scattered about. - Prompt on the `read` that waits for it: `read -r -p "Press Enter to continue, or -c to bail"`, not an `echo` followed by a bare `read -r` that silently fills `$REPLY`. - Descriptive names, and never a magic environment variable as a scratch variable. `WORK_DIR`, not - `TMPDIR` — that one is read by `mktemp` and `git`, so assigning it moves everyone else's temporary files too. -- Comments explain *why*. The `# help:` block explains *what*, and it is the only user-facing documentation of a - command. + `TMPDIR` — that one is read by `mktemp` and `git`, so assigning it moves everyone else's + temporary files too. +- Comments explain *why*. The `# help:` block explains *what*, and it is the only user-facing + documentation of a command. Its first line is the summary in `dev help`. - Anything creating a temporary directory cleans it up: `trap 'rm -rf "$WORK_DIR"' EXIT`. - Anything destructive shows what it is about to do and waits for Enter first. ## Adding a command -1. Create `bin/dev-something`, `chmod +x`, with the standard header. -2. Give it a `# help:` block. The first line is the one-line summary in `dev help`; the whole block is what - `dev help something` and `dev something --help` print. -3. Wire up `--help` with the standard guard, which re-enters the dispatcher rather than printing anything itself: - ```bash - if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then - exec "$(dirname "$0")/dev" help "${0##*/dev-}" - fi - ``` -4. Write `tests/test-something.sh`. -5. Add a row to the table in `README.md`. - -Homebrew installs everything matching `bin/dev*` and `dev help` globs for it, so there is nothing else to register. - -## Tests - -Plain bash scripts, no framework. One `tests/test-.sh` per command, executable, run by -`make test`, which loops over `tests/test-*.sh` and stops at the first script to exit non-zero. Run one directly while -working on it: `./tests/test-clone.sh`. - -Every test sources `tests/helpers.sh`, which provides: - -- `make_workdir` — `mktemp -d` into `$WORKDIR` with an `EXIT` trap, and puts `$WORKDIR/stub` at the front of `$PATH`. -- `write_stub ` — writes an executable stub from stdin into the stub directory. -- `expect ` — exact-match assertion. -- `expect_contains ` — substring assertion, which is what most output checks want. -- `fail ` — records a failure and carries on. -- `finish ` — exits non-zero if anything failed, otherwise prints `PASS: `. - -Assertions report and continue rather than aborting, so one run tells you everything that is broken instead of only the -first thing. That is why `finish` is what decides the exit status, and why every test must end with a `finish` line. - -The commands here talk to git, ssh, pip, aws-vault, pyenv, `gh` and the 1Password CLI. Tests stub all of them with -`write_stub`, so they need no credentials, touch no real repos or servers, and write nothing outside their temporary -directory. A stub usually logs its arguments to a file the test then asserts against: +`bin/dev-something`, `chmod +x`, standard header. Then: a `# help:` block, the `--help` guard +which re-enters the dispatcher rather than printing anything itself, a `tests/test-something.sh`, +and a row in the README's command table. ```bash -write_stub git <<'STUB' -#!/usr/bin/env bash -set -euo pipefail -echo "$*" >> "$STUB_GIT_LOG" -STUB - -export STUB_GIT_LOG="$WORKDIR/git.log" +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi ``` -Test the behaviour worth protecting — which arguments the command builds, which paths it writes, what it refuses to do, -and that it cleans up after a failure — rather than restating the implementation. Each test opens with a comment saying -what is worth checking in that command and why. Commands that wait for Enter are driven with `printf '\n' | ...`. +## Tests -## Checks +Plain bash, no framework. One executable `tests/test-.sh` per command, sourcing +`tests/helpers.sh` for its assertions and stub scaffolding. -`make check` — shellcheck, `shfmt --diff`, then the tests — is exactly what CI runs, so a green -`make check` locally means a green build. `make format` fixes the formatting it complains about. CI installs shfmt with -`go install`, because the GitHub runner image ships shellcheck but not shfmt. +- Assertions report and carry on rather than aborting, so one run tells you everything that is + broken. `finish` is what decides the exit status, so every test ends with a `finish` line. +- Stub every external command with `write_stub`, so tests need no credentials, touch no real repos + or servers, and write nothing outside `$WORKDIR`. A stub usually logs its arguments to a file + the test then asserts against. +- Test the behaviour worth protecting — which arguments the command builds, which paths it writes, + what it refuses to do, and that it cleans up after a failure — rather than restating the + implementation. +- Each test opens with a comment saying what is worth checking in that command and why. +- Commands that wait for Enter are driven with `printf '\n' | ...`. ## Docs -`docs/development.md` covers the contributor workflow: tooling, testing a branch through the Homebrew tap, and -releasing. `docs/tofu-env.md` explains the `dev tofu env` workflow. The README is deliberately limited to installation -and usage — new documentation goes in `docs/`. +The README is deliberately limited to installation and usage. New documentation goes in `docs/`. diff --git a/Formula/devtools.rb b/Formula/devtools.rb index cf90962..b1870d5 100644 --- a/Formula/devtools.rb +++ b/Formula/devtools.rb @@ -10,9 +10,10 @@ class Devtools < Formula # keys its cache on: bump it to ship a release. While testing a branch, "brew fetch --force # devtools" clears the cached clone without a bump. TAP_CHECKOUT = Pathname.new(__dir__).parent.freeze - TAP_BRANCH = Utils.popen_read("git", "-C", TAP_CHECKOUT, "branch", "--show-current").strip.freeze - url "file://#{TAP_CHECKOUT}", using: :git, branch: TAP_BRANCH + # No "branch:" here - cloning a local repo follows its HEAD, which is whichever branch the tap + # is currently on, which is exactly what testing a branch needs. + url "file://#{TAP_CHECKOUT}", using: :git version "1.0.0" depends_on "aws-vault" diff --git a/bin/dev-clean-branches b/bin/dev-clean-branches index 53f6a68..e2e71a5 100755 --- a/bin/dev-clean-branches +++ b/bin/dev-clean-branches @@ -5,7 +5,7 @@ IFS=$'\n\t' # help: Delete merged local branches, including squash-merged ones, and prune remotes # # Usage: -# dev clean-branches [--yes] +# dev clean-branches # # Deletes local branches whose changes have landed on the default branch. Squash-merged branches # are found too, which "git branch --merged" cannot do on its own. main, master, dev and the @@ -17,11 +17,6 @@ fi PROTECTED_BRANCHES="main master dev" -ASSUME_YES=0 -if [ "${1:-}" = "-y" ] || [ "${1:-}" = "--yes" ]; then - ASSUME_YES=1 -fi - # If the remote repo was added without the usual clone, then HEAD might be missing. A quick fix # can restore HEAD to the expected branch. if [ ! -f .git/refs/remotes/origin/HEAD ]; then @@ -63,9 +58,7 @@ if [ "${#BRANCHES[@]}" -gt 0 ]; then printf '%s\n' "${BRANCHES[@]}" echo - if [ "$ASSUME_YES" -ne 1 ]; then - read -r -p "Press Enter to delete the above branches, or -c to bail" - fi + read -r -p "Press Enter to delete the above branches, or -c to bail" # Git refuses to delete the branch you are standing on. case " ${BRANCHES[*]} " in diff --git a/docs/development.md b/docs/development.md index aa51e30..b301bd6 100644 --- a/docs/development.md +++ b/docs/development.md @@ -3,16 +3,6 @@ How to work on the tools themselves. For the house style, the shell conventions and how the tests are put together, see [AGENTS.md](../AGENTS.md). -## Adding a tool - -New tools go in `bin/` named `dev-something`, with a `# help: one line summary` comment near the -top. `dev help` picks them up automatically, and Homebrew installs anything matching `bin/dev*`, -so there's no list to keep in sync. Every command has a test in `tests/`, which stubs out the -commands it calls so it needs no credentials. - -[AGENTS.md](../AGENTS.md) has the step by step: the script header, the `--help` guard, and how the -tests are put together. - ## Tooling The tools needed to work on this repo are shellcheck and shfmt. There's no virtualenv, because diff --git a/tests/test-clean-branches.sh b/tests/test-clean-branches.sh index caeaaeb..646825c 100755 --- a/tests/test-clean-branches.sh +++ b/tests/test-clean-branches.sh @@ -47,7 +47,7 @@ git merge --quiet --squash squashed-branch >/dev/null 2>&1 git commit --quiet -m "Squash merge of squashed-branch" git push --quiet origin main -"$CLEAN_BRANCHES" --yes >/dev/null +printf '\n' | "$CLEAN_BRANCHES" >/dev/null expect "merged and squash-merged branches go, the unmerged one stays" \ "main unmerged-branch " "$(git branch --format "%(refname:short)" | sort | tr '\n' ' ')" @@ -55,7 +55,7 @@ expect "merged and squash-merged branches go, the unmerged one stays" \ # A second run has nothing to delete, which used to abort the script when grep found no matches. git switch --quiet main git branch --quiet -D unmerged-branch -SECOND_RUN=$("$CLEAN_BRANCHES" --yes) +SECOND_RUN=$(printf '\n' | "$CLEAN_BRANCHES") expect_contains "expected a clean repo to report nothing to remove" \ "$SECOND_RUN" "No local branches need removing" From f3385b6ea8332f52f20d2c75f3da23bbdc37a9db Mon Sep 17 00:00:00 2001 From: Kyle Stevenson Date: Mon, 14 Sep 2026 13:37:42 +0100 Subject: [PATCH 32/32] removed all the changes to the scripts and updated tests --- Formula/devtools.rb | 2 - README.md | 23 +++--- bin/dev-archive-repo | 35 +++------ bin/dev-aws-login | 8 +- bin/dev-clean-branches | 41 ++--------- bin/dev-clone | 118 ++++++----------------------- bin/dev-tofu | 127 ++------------------------------ bin/dev-unlock-server | 65 ++++------------ bin/dev-update-aws-config | 40 +++------- bin/dev-wipeenv | 16 +--- docs/tofu-env.md | 23 ------ tests/test-archive-repo.sh | 34 ++------- tests/test-aws-login.sh | 19 ++--- tests/test-clean-branches.sh | 19 +---- tests/test-clone.sh | 60 +++------------ tests/test-tofu.sh | 99 +++---------------------- tests/test-unlock-server.sh | 47 +++--------- tests/test-update-aws-config.sh | 44 ++++------- tests/test-wipeenv.sh | 13 +--- 19 files changed, 150 insertions(+), 683 deletions(-) delete mode 100644 docs/tofu-env.md diff --git a/Formula/devtools.rb b/Formula/devtools.rb index b1870d5..8c4e121 100644 --- a/Formula/devtools.rb +++ b/Formula/devtools.rb @@ -17,8 +17,6 @@ class Devtools < Formula version "1.0.0" depends_on "aws-vault" - depends_on "gh" - depends_on "jq" depends_on "opentofu" # The 1Password CLI is a cask, which formulae can't depend on, and pyenv/virtualenvwrapper are diff --git a/README.md b/README.md index 243e40c..2b2c78c 100644 --- a/README.md +++ b/README.md @@ -39,19 +39,16 @@ $ dev tofu --help Each command explains itself, so the list below is a map rather than a manual. -| Command | What it does | -|-------------------------|-------------------------------------------------------------------------| -| `dev clone` | Clone a repo and set up virtualenvwrapper for it | -| `dev clean-branches` | Delete merged local branches, squash-merges included, and prune remotes | -| `dev tofu` | Run tofu with the devsoc-tofu profile, and manage project env vars | -| `dev aws-login` | Open the AWS console via aws-vault | -| `dev update-aws-config` | Rewrite `~/.aws/config` from the 1Password template | -| `dev unlock-server` | Unlock the encrypted root filesystem on one or more servers | -| `dev archive-repo` | Mirror a repo to the archive server, then archive it on GitHub | -| `dev wipeenv` | Uninstall every package in the active virtualenv | - -Managing a project's environment variables has a workflow of its own — see -[docs/tofu-env.md](docs/tofu-env.md). +| Command | What it does | +|-------------------------|-----------------------------------------------------| +| `dev clone` | Clone a repo and set up virtualenvwrapper for it | +| `dev clean-branches` | Delete merged local branches and prune remotes | +| `dev tofu` | Run tofu with the devsoc-tofu profile | +| `dev aws-login` | Open the AWS console via aws-vault | +| `dev update-aws-config` | Rewrite `~/.aws/config` from the 1Password template | +| `dev unlock-server` | Unlock the encrypted root filesystem on a server | +| `dev archive-repo` | Mirror a repo to the archive server | +| `dev wipeenv` | Uninstall every package in the active virtualenv | ## Development diff --git a/bin/dev-archive-repo b/bin/dev-archive-repo index a5a930e..ce8852d 100755 --- a/bin/dev-archive-repo +++ b/bin/dev-archive-repo @@ -2,50 +2,35 @@ set -euo pipefail IFS=$'\n\t' -# help: Mirror a repo to the archive server, then archive it on GitHub +# help: Mirror a repo to the archive server # # Usage: -# dev archive-repo [org/]repo +# dev archive-repo repo # -# Mirrors every branch and tag to the archive server, then archives the repo on GitHub, which -# makes it read-only. A repo name given without an org is assumed to be under developersociety. +# Mirrors every branch and tag of a developersociety repo to the archive server. if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi -DEFAULT_ORG="developersociety" +ORG="developersociety" ARCHIVE_HOST="smirkenorff.devsoc.org" if [ "$#" -ne 1 ]; then - echo "Usage: dev archive-repo [org/]repo" + echo "Usage: dev archive-repo repo" exit 1 fi -# Handle org/repo, and repo REPO_ARG="$1" -case "$REPO_ARG" in -*/*) REPO_NAME="$REPO_ARG" ;; -*) REPO_NAME="$DEFAULT_ORG/$REPO_ARG" ;; -esac -PROJECT_NAME="${REPO_NAME##*/}" - -echo "I'm going to mirror: $REPO_NAME" -echo "To the archive server: $ARCHIVE_HOST" -echo "And then archive it on GitHub, which makes it read-only." -echo -read -r -p "Press Enter to continue, or -c to bail" + +echo "Archiving $REPO_ARG" # Not $TMPDIR - that is the standard var mktemp and git read, and clobbering it would move # everyone else's temporary files in here too. WORK_DIR=$(mktemp -d) trap 'rm -rf "$WORK_DIR"' EXIT -CLONE_DIR="$WORK_DIR/$PROJECT_NAME.git" - -git clone --bare "git@github.com:$REPO_NAME.git" "$CLONE_DIR" -git -C "$CLONE_DIR" push --mirror "git@$ARCHIVE_HOST:archive/$PROJECT_NAME.git" - -gh repo archive "$REPO_NAME" --yes +CLONE_DIR="$WORK_DIR/$REPO_ARG.git" -echo "Done - $REPO_NAME is mirrored and archived." +git clone --bare "git@github.com:$ORG/$REPO_ARG.git" "$CLONE_DIR" +git -C "$CLONE_DIR" push --mirror "git@$ARCHIVE_HOST:archive/$REPO_ARG.git" diff --git a/bin/dev-aws-login b/bin/dev-aws-login index e050a1b..8cf5beb 100755 --- a/bin/dev-aws-login +++ b/bin/dev-aws-login @@ -5,14 +5,12 @@ IFS=$'\n\t' # help: Open the AWS console via aws-vault # # Usage: -# dev aws-login [profile] +# dev aws-login # -# Defaults to the profile in $AWS_VAULT_PROFILE, or "devsoc". +# Arguments are passed straight through to "aws-vault login". if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi -DEFAULT_PROFILE="${AWS_VAULT_PROFILE:-devsoc}" - -exec aws-vault login -- "${@:-$DEFAULT_PROFILE}" +exec aws-vault login -- "$@" diff --git a/bin/dev-clean-branches b/bin/dev-clean-branches index e2e71a5..b05a07b 100755 --- a/bin/dev-clean-branches +++ b/bin/dev-clean-branches @@ -2,14 +2,13 @@ set -euo pipefail IFS=$'\n\t' -# help: Delete merged local branches, including squash-merged ones, and prune remotes +# help: Delete merged local branches and prune remotes # # Usage: # dev clean-branches # -# Deletes local branches whose changes have landed on the default branch. Squash-merged branches -# are found too, which "git branch --merged" cannot do on its own. main, master, dev and the -# repo's own default branch are never deleted. +# Deletes local branches which have been merged into the default branch. main, master, dev and +# the repo's own default branch are never deleted. if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" @@ -25,31 +24,15 @@ fi DEFAULT_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD | sed -e "s|^refs/remotes/origin/||") -# Compare against the remote branch rather than the local one, which may be stale or absent. -BASE_BRANCH="origin/$DEFAULT_BRANCH" - -is_squash_merged() { - # A squash-merge leaves no ancestry behind, so "git branch --merged" cannot see it. Replaying - # the branch's tree as a single commit on top of the merge base gives git something it can - # recognise: if that commit is already present in the base branch, the changes have landed. - local branch="$1" - local merge_base squashed - - merge_base=$(git merge-base "$BASE_BRANCH" "$branch") - squashed=$(git commit-tree "$branch^{tree}" -p "$merge_base" -m "squash-merge check") - - ! git cherry "$BASE_BRANCH" "$squashed" | grep -q "^+" -} - +# Collecting the branches into an array rather than filtering with grep, which exits non-zero +# when everything has been filtered out and takes the whole script down with it. BRANCHES=() -for BRANCH in $(git branch --format "%(refname:short)"); do +for BRANCH in $(git branch --merged "$DEFAULT_BRANCH" --format "%(refname:short)"); do case " $PROTECTED_BRANCHES $DEFAULT_BRANCH " in *" $BRANCH "*) continue ;; esac - if git merge-base --is-ancestor "$BRANCH" "$BASE_BRANCH" || is_squash_merged "$BRANCH"; then - BRANCHES+=("$BRANCH") - fi + BRANCHES+=("$BRANCH") done if [ "${#BRANCHES[@]}" -gt 0 ]; then @@ -57,17 +40,9 @@ if [ "${#BRANCHES[@]}" -gt 0 ]; then echo printf '%s\n' "${BRANCHES[@]}" echo - read -r -p "Press Enter to delete the above branches, or -c to bail" - # Git refuses to delete the branch you are standing on. - case " ${BRANCHES[*]} " in - *" $(git branch --show-current) "*) git switch "$DEFAULT_BRANCH" ;; - esac - - # -D rather than -d, because squash-merged branches are not ancestors of the base branch and - # git would refuse to delete them. is_squash_merged has already confirmed the work landed. - git branch -D "${BRANCHES[@]}" + git branch -d "${BRANCHES[@]}" echo "Done." else diff --git a/bin/dev-clone b/bin/dev-clone index a5cd711..4d90071 100755 --- a/bin/dev-clone +++ b/bin/dev-clone @@ -5,14 +5,10 @@ IFS=$'\n\t' # help: Clone a repo and set up virtualenvwrapper for it # # Usage: -# dev clone [--vscode] [org/]repo +# dev clone [org/]repo # -# Accepts a bare repo name, "org/repo", or a URL pasted from the browser. Requires -# virtualenvwrapper, with $PROJECT_HOME set. The Python version comes from .python-version or -# tox.ini's basepython, and repos which don't look like Python projects skip the virtualenv. -# -# --vscode also writes a .code-workspace file pointing at the project's interpreter, and hides it -# from git. +# Requires virtualenvwrapper, with $PROJECT_HOME set. A repo name given without an org is assumed +# to be under developersociety. The Python version comes from tox.ini's basepython. if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" @@ -20,33 +16,16 @@ fi DEFAULT_ORG="developersociety" -MAKE_VSCODE_WORKSPACE=0 -if [ "${1:-}" = "--vscode" ]; then - MAKE_VSCODE_WORKSPACE=1 - shift -fi +# shellcheck source=/dev/null # path is set per-machine +source "$VIRTUALENVWRAPPER_SCRIPT" if [ "$#" -ne 1 ]; then - echo "Usage: dev clone [--vscode] [org/]repo" - exit 1 -fi - -if [ -z "${PROJECT_HOME:-}" ] || [ -z "${VIRTUALENVWRAPPER_SCRIPT:-}" ]; then - echo "\$PROJECT_HOME and \$VIRTUALENVWRAPPER_SCRIPT must be set." - echo "Is virtualenvwrapper installed and set up in your shell?" + echo "Usage: dev clone [org/]repo" exit 1 fi -# shellcheck source=/dev/null -source "$VIRTUALENVWRAPPER_SCRIPT" - -# Accept anything you might have in your clipboard: repo, org/repo, or a URL from the browser. +# Handle org/repo, and repo REPO_ARG="$1" -REPO_ARG="${REPO_ARG#https://github.com/}" -REPO_ARG="${REPO_ARG#git@github.com:}" -REPO_ARG="${REPO_ARG%/}" -REPO_ARG="${REPO_ARG%.git}" - case "$REPO_ARG" in */*) REPO_NAME="$REPO_ARG" ;; *) REPO_NAME="$DEFAULT_ORG/$REPO_ARG" ;; @@ -54,8 +33,8 @@ esac PROJECT_NAME="${REPO_NAME##*/}" GIT_URI="git@github.com:$REPO_NAME.git" +# shellcheck disable=SC2153 # PROJECT_HOME is virtualenvwrapper's, not a typo of PROJECT_NAME PROJECT_DIR="$PROJECT_HOME/$PROJECT_NAME" -VENV_DIR="${WORKON_HOME:-$HOME/.virtualenvs}/$PROJECT_NAME" if [ -e "$PROJECT_DIR" ]; then echo "Target directory already exists:" @@ -63,46 +42,6 @@ if [ -e "$PROJECT_DIR" ]; then exit 1 fi -is_python_project() { - [ -f tox.ini ] || [ -f pyproject.toml ] || [ -f requirements.txt ] || [ -f .python-version ] -} - -project_python_version() { - # Projects pin their Python version in whichever place was fashionable when they started. - if [ -f .python-version ]; then - head -n 1 .python-version - elif [ -f tox.ini ]; then - sed -n -e 's/^[[:space:]]*basepython[[:space:]]*=[[:space:]]*python//p' tox.ini | head -n 1 - fi -} - -write_vscode_workspace() { - local workspace_file="$PROJECT_DIR/$PROJECT_NAME.code-workspace" - local interpreter_setting="" - - if [ -x "$VENV_DIR/bin/python" ]; then - interpreter_setting="\"python.defaultInterpreterPath\": \"$VENV_DIR/bin/python\"" - fi - - cat >"$workspace_file" <>"$PROJECT_DIR/.git/info/exclude" - - echo "VS Code workspace written to: $workspace_file" -} - echo "I'm going to clone: $GIT_URI" echo "Into this directory: $PROJECT_DIR" echo "And setup virtualenvwrapper for you." @@ -112,32 +51,23 @@ read -r -p "Press Enter to continue..." git clone "$GIT_URI" "$PROJECT_DIR" cd "$PROJECT_DIR" -if is_python_project; then - # mkproject fails with super strict mode - so we need to allow unbound variables at this point - set +u - - PYTHON_VERSION=$(project_python_version) - - if [ -n "$PYTHON_VERSION" ] && command -v pyenv >/dev/null; then - LATEST_PYTHON=$(pyenv latest "$PYTHON_VERSION") - PYTHON_EXE=$(PYENV_VERSION=$LATEST_PYTHON pyenv which python) - VIRTUALENV_EXE=$(PYENV_VERSION=$LATEST_PYTHON pyenv which virtualenv) - VIRTUALENVWRAPPER_VIRTUALENV=$VIRTUALENV_EXE mkproject --force --python="$PYTHON_EXE" \ - "$PROJECT_NAME" - else - mkproject --force "$PROJECT_NAME" - fi - - set -u - FINAL_MESSAGE="Done - to activate this project: workon $PROJECT_NAME" +# mkproject fails with super strict mode - so we need to allow unbound variables at this point +set +u + +# The -f test only stops grep complaining about a missing tox.ini - a repo without one takes the +# same branch either way. +if [ -f tox.ini ] && grep --fixed-strings --silent "basepython" tox.ini; then + PYTHON_VERSION=$(sed -n -e 's/^[[:space:]]*basepython[[:space:]]*=[[:space:]]*//p' tox.ini | + head -n 1) + LATEST_PYTHON=$(pyenv latest "${PYTHON_VERSION#python}") + VIRTUALENV_EXE=$(PYENV_VERSION=$LATEST_PYTHON pyenv which virtualenv) + VIRTUALENVWRAPPER_VIRTUALENV=$VIRTUALENV_EXE mkproject --force --python="$PYTHON_VERSION" \ + "$PROJECT_NAME" else - FINAL_MESSAGE="Done - this doesn't look like a Python project, so no virtualenv was created." + mkproject --force "$PROJECT_NAME" fi -echo +set -u -if [ "$MAKE_VSCODE_WORKSPACE" = 1 ]; then - write_vscode_workspace -fi - -echo "$FINAL_MESSAGE" +echo +echo "Done - to activate this project: workon $PROJECT_NAME" diff --git a/bin/dev-tofu b/bin/dev-tofu index 62fa8c2..d466c6f 100755 --- a/bin/dev-tofu +++ b/bin/dev-tofu @@ -2,134 +2,17 @@ set -euo pipefail IFS=$'\n\t' -# help: Run tofu with the devsoc-tofu AWS profile, and manage project env vars +# help: Run tofu with the devsoc-tofu AWS profile # # Usage: -# dev tofu Run tofu, initialising the directory first if needed -# dev tofu all Run tofu in every project directory, one at a time -# dev tofu env List the project's env vars and their values -# dev tofu env NAME Print the value of a single env var -# dev tofu env set NAME [VALUE] Create or replace an env var, prompting if no value given +# dev tofu # -# Env vars live in the tofu state as "random_password" resources declared in the project's -# envvars.tf, so "env set" removes and re-imports the resource rather than applying a change. -# A "dev tofu apply" is still needed afterwards to get the new value onto the running service. -# -# Set $AWS_VAULT_PROFILE to use a profile other than devsoc-tofu. Use "tofu -help" for tofu's own -# help, as "--help" is handled here. +# Use "tofu -help" for tofu's own help, as "--help" is handled here. if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi -PROFILE="${AWS_VAULT_PROFILE:-devsoc-tofu}" - -tofu_exec() { - aws-vault exec "$PROFILE" -- tofu "$@" -} - -ensure_initialised() { - if [ ! -d .terraform ]; then - echo "No .terraform directory found - running 'tofu init' first." - tofu_exec init - fi -} - -# Env vars are named in upper case, which is what separates them from the random_password -# resources tofu uses internally for things like database passwords. -# ponytail: naming convention, not a real marker. Tag the resources if it ever mis-sorts one. -env_list() { - tofu_exec show -json | jq -r ' - .values.root_module.resources[] - | select(.type == "random_password") - | select(.name | test("^[A-Z][A-Z0-9_]*$")) - | "\(.name)=\(.values.result)" - ' -} - -env_get() { - local name="$1" - local value - - value=$(env_list | sed -n -e "s/^$name=//p") - - if [ -z "$value" ]; then - echo "No env var called '$name' in this project's state." >&2 - exit 1 - fi - - echo "$value" -} - -env_set() { - local name="$1" - local value="${2:-}" - - if [ -z "$value" ]; then - read -r -s -p "Value for $name: " value - echo - fi - - # A variable already in the state has to be removed before it can be re-imported. - if tofu_exec state list "random_password.$name" 2>/dev/null | grep -q .; then - tofu_exec state rm "random_password.$name" - fi - - tofu_exec import "random_password.$name" "$value" - - echo - echo "Imported $name. Run 'dev tofu apply' to roll it out." -} - -run_env_command() { - ensure_initialised - - local action="${1:-}" - - case "$action" in - "") - env_list - ;; - set) - if [ $# -lt 2 ]; then - echo "Usage: dev tofu env set NAME [VALUE]" >&2 - exit 1 - fi - env_set "$2" "${3:-}" - ;; - *) - env_get "$action" - ;; - esac -} - -run_in_every_project() { - # Projects are the directories holding their own tofu.tf, which is what allthetofu.sh used to - # find. Run them one at a time so apply's confirmation prompts stay readable. - local project - - for project in */; do - if [ ! -f "$project/tofu.tf" ]; then - continue - fi - - echo "=== ${project%/} ===" - (cd "$project" && ensure_initialised && tofu_exec "$@") - echo - done -} +PROFILE="devsoc-tofu" -case "${1:-}" in -env) - shift - run_env_command "$@" - ;; -all) - shift - run_in_every_project "$@" - ;; -*) - ensure_initialised - tofu_exec "$@" - ;; -esac +exec aws-vault exec "$PROFILE" -- tofu "$@" diff --git a/bin/dev-unlock-server b/bin/dev-unlock-server index 6f662ca..5c3ed55 100755 --- a/bin/dev-unlock-server +++ b/bin/dev-unlock-server @@ -2,14 +2,12 @@ set -euo pipefail IFS=$'\n\t' -# help: Unlock the encrypted root filesystem on one or more servers +# help: Unlock the encrypted root filesystem on a server # # Usage: -# dev unlock-server hostname.devsoc.org [hostname.devsoc.org ...] +# dev unlock-server hostname.devsoc.org # -# Reads each server's passphrase from 1Password and sends it to the initramfs SSH server, then -# waits for the machine to finish booting before moving on to the next one. Set -# $DEV_UNLOCK_TIMEOUT to wait longer than the default 180 seconds for a slow server. +# Reads the server's passphrase from 1Password and sends it to the initramfs SSH server. if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" @@ -17,56 +15,19 @@ fi OP_VAULT="aizi3l3vxjc52mboshwj7bbytq" KNOWN_HOSTS_FILE="$HOME/.ssh/known_hosts.cryptroot-unlock" -BOOT_TIMEOUT_SECONDS="${DEV_UNLOCK_TIMEOUT:-180}" -BOOT_POLL_SECONDS=5 -if [ $# -lt 1 ]; then - echo "Usage: dev unlock-server hostname.devsoc.org [hostname.devsoc.org ...]" +if [ "$#" -ne 1 ]; then + echo "Usage: dev unlock-server hostname.devsoc.org" >&2 exit 1 fi -if ! op account get >/dev/null 2>&1; then - echo "1Password CLI not usable. Install it with 'brew install --cask 1password-cli'," - echo "or sign in with: eval \$(op signin)" - exit 1 -fi - -send_passphrase() { - local host="$1" - local passphrase - passphrase=$(op read "op://$OP_VAULT/$host/password") - - # The initramfs SSH server has its own host key, so it gets its own known_hosts file. - echo -n "$passphrase" | - ssh -o UserKnownHostsFile="$KNOWN_HOSTS_FILE" \ - -o StrictHostKeyChecking=accept-new \ - -o BatchMode=yes \ - "root@$host" cryptroot-unlock -} - -wait_for_boot() { - # The initramfs SSH server disappears the moment the disk unlocks, so reaching the real host's - # SSH is what actually confirms the machine finished booting. - local host="$1" - local deadline=$(($(date +%s) + BOOT_TIMEOUT_SECONDS)) - - while [ "$(date +%s)" -lt "$deadline" ]; do - if ssh -o BatchMode=yes -o ConnectTimeout=5 "$host" true 2>/dev/null; then - return 0 - fi - sleep "$BOOT_POLL_SECONDS" - done - - return 1 -} +HOST="$1" -for HOST in "$@"; do - echo "Unlocking $HOST..." - send_passphrase "$HOST" +LUKS_PASSPHRASE=$(op read "op://$OP_VAULT/$HOST/password") - if wait_for_boot "$HOST"; then - echo "$HOST is up." - else - echo "$HOST did not come back within ${BOOT_TIMEOUT_SECONDS}s - check it manually." >&2 - fi -done +# The initramfs SSH server has its own host key, so it gets its own known_hosts file. +echo -n "$LUKS_PASSPHRASE" | + ssh -o UserKnownHostsFile="$KNOWN_HOSTS_FILE" \ + -o StrictHostKeyChecking=accept-new \ + -o BatchMode=yes \ + "root@$HOST" cryptroot-unlock diff --git a/bin/dev-update-aws-config b/bin/dev-update-aws-config index 6fb3fcc..e8530e6 100755 --- a/bin/dev-update-aws-config +++ b/bin/dev-update-aws-config @@ -5,54 +5,32 @@ IFS=$'\n\t' # help: Rewrite ~/.aws/config from the 1Password template # # Usage: -# dev update-aws-config [username] +# dev update-aws-config username # -# Shows a diff and asks before replacing anything. The username defaults to $USER, and the last -# 5 backups are kept alongside the config. +# The existing config is moved aside with a timestamped name before the new one is written. if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" fi -BACKUPS_TO_KEEP=5 CONFIG_FILE="$HOME/.aws/config" -CONFIG_USERNAME="${1:-$USER}" - -if ! op account get >/dev/null 2>&1; then - echo "1Password CLI not usable. Install it with 'brew install --cask 1password-cli'," - echo "or sign in with: eval \$(op signin)" +if [ "$#" -ne 1 ]; then + echo "Usage: dev update-aws-config username" exit 1 fi -mkdir -p "$HOME/.aws" - -# Render to a temporary file first, so a failed "op read" can't leave you with no config at all. -TMPFILE=$(mktemp) -trap 'rm -f "$TMPFILE"' EXIT +CONFIG_USERNAME="$1" -op read "op://Shared/AWS Config Template/notesPlain" | - sed -e "s|USERNAME|$CONFIG_USERNAME|g" >"$TMPFILE" +mkdir -p "$HOME/.aws" if [ -f "$CONFIG_FILE" ]; then - if diff -u "$CONFIG_FILE" "$TMPFILE"; then - echo "Config is already up to date for '$CONFIG_USERNAME'." - exit 0 - fi - - echo - read -r -p "Press Enter to apply the above changes for '$CONFIG_USERNAME', or -c to bail" - TIMESTAMP=$(date -u +"%Y%m%dT%H%M%SZ") - cp "$CONFIG_FILE" "$CONFIG_FILE.old.$TIMESTAMP" echo "Backup of existing config saved to: $CONFIG_FILE.old.$TIMESTAMP" + mv "$CONFIG_FILE" "$CONFIG_FILE.old.$TIMESTAMP" fi -mv "$TMPFILE" "$CONFIG_FILE" - -# Backups otherwise accumulate forever, one per run. -{ ls -1t "$CONFIG_FILE".old.* 2>/dev/null || true; } | - tail -n +$((BACKUPS_TO_KEEP + 1)) | - xargs rm -f +op read "op://Shared/AWS Config Template/notesPlain" | + sed -e "s|USERNAME|$CONFIG_USERNAME|g" >"$CONFIG_FILE" echo "Config file updated!" diff --git a/bin/dev-wipeenv b/bin/dev-wipeenv index 9f2e098..4f3e1d7 100755 --- a/bin/dev-wipeenv +++ b/bin/dev-wipeenv @@ -7,7 +7,7 @@ IFS=$'\n\t' # Usage: # dev wipeenv # -# Lists what it is about to remove and asks first. pip, setuptools and wheel are left alone. +# pip, setuptools and wheel are left alone. if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then exec "$(dirname "$0")/dev" help "${0##*/dev-}" @@ -23,17 +23,7 @@ fi # # Need to make sure not to uninstall pip itself. List of things to avoid comes from docs for # "pip freeze --all" -PACKAGES=$(pip list --format=freeze | grep -v "^pip=\|^setuptools=\|^wheel=" || true) - -if [ -z "$PACKAGES" ]; then +if ! pip list --format=freeze | grep -v "^pip=\|^setuptools=\|^wheel=" | + xargs pip uninstall -y; then echo "Nothing to remove" - exit 0 fi - -echo "Will uninstall the following from $VIRTUAL_ENV:" -echo -echo "$PACKAGES" -echo -read -r -p "Press Enter to uninstall the above packages, or -c to bail" - -echo "$PACKAGES" | xargs pip uninstall -y diff --git a/docs/tofu-env.md b/docs/tofu-env.md deleted file mode 100644 index 2a25027..0000000 --- a/docs/tofu-env.md +++ /dev/null @@ -1,23 +0,0 @@ -# Project environment variables - -`dev tofu env` reads and sets the environment variables for a project. The workflow behind it -isn't obvious, which is why it gets a page of its own. - -A project's environment variables live in the tofu state as `random_password` resources declared -in the project's `envvars.tf`. Reading and setting them used to mean copy-pasting raw -`tofu show -json | jq ...` and `state rm` / `import` incantations from the comments at the top of -each `envvars.tf`. Instead: - -```console -$ dev tofu env # list every variable and its value -$ dev tofu env SENTRY_AUTH_TOKEN # print one value -$ dev tofu env set SENTRY_AUTH_TOKEN # prompt for the value, then import it -``` - -Three things to know: - -- Setting a variable removes it from the state and re-imports it, so a `dev tofu apply` is still - needed to get the new value onto the running service. -- The variable has to have a `random_password` resource in `envvars.tf` before it can be - imported. -- Variables are told apart from tofu's internal passwords by their upper case names. diff --git a/tests/test-archive-repo.sh b/tests/test-archive-repo.sh index 9b86d2b..7a17776 100755 --- a/tests/test-archive-repo.sh +++ b/tests/test-archive-repo.sh @@ -2,9 +2,9 @@ set -euo pipefail IFS=$'\n\t' -# dev-archive-repo pushes to a server and makes a GitHub repo read-only, so the interesting parts -# are that it aims at the right places and that it cleans up its temporary clone even when the -# push fails. Runs against stubbed git and gh. +# dev-archive-repo pushes to a server, so the interesting parts are that it aims at the right +# places and that it cleans up its temporary clone even when the push fails. Runs against a +# stubbed git. BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" # shellcheck source=tests/helpers.sh @@ -29,14 +29,7 @@ if [ "${1:-}" = "-C" ]; then fi STUB -write_stub gh <<'STUB' -#!/usr/bin/env bash -set -euo pipefail -echo "$*" >> "$STUB_GH_LOG" -STUB - export STUB_GIT_LOG="$WORKDIR/git.log" -export STUB_GH_LOG="$WORKDIR/gh.log" # mktemp honours $TMPDIR, so pointing it somewhere known makes the cleanup checkable. mkdir -p "$WORKDIR/tmp" @@ -47,30 +40,17 @@ count_temp_entries() { } : >"$STUB_GIT_LOG" -: >"$STUB_GH_LOG" -printf '\n' | "$BINDIR/dev" archive-repo oldproject >/dev/null +"$BINDIR/dev" archive-repo oldproject >/dev/null -expect "a bare name is assumed to be a developersociety repo" \ +expect "the repo is cloned from the developersociety org" \ "1" "$(grep -c "clone --bare git@github.com:developersociety/oldproject.git" "$STUB_GIT_LOG")" expect "the mirror is pushed to the archive server" \ "1" "$(grep -c "push --mirror git@smirkenorff.devsoc.org:archive/oldproject.git" "$STUB_GIT_LOG")" -expect "the repo is archived on GitHub afterwards" \ - "repo archive developersociety/oldproject --yes" "$(cat "$STUB_GH_LOG")" expect "the temporary clone is cleaned up" "0" "$(count_temp_entries)" -: >"$STUB_GIT_LOG" -: >"$STUB_GH_LOG" -printf '\n' | "$BINDIR/dev" archive-repo someorg/theirproject >/dev/null -expect "an org/repo argument is used as given" \ - "1" "$(grep -c "clone --bare git@github.com:someorg/theirproject.git" "$STUB_GIT_LOG")" -expect "the archive path uses the repo name without the org" \ - "1" "$(grep -c "archive/theirproject.git" "$STUB_GIT_LOG")" - -: >"$STUB_GH_LOG" -if printf '\n' | STUB_PUSH_FAILS=1 "$BINDIR/dev" archive-repo brokenproject >/dev/null 2>&1; then +if STUB_PUSH_FAILS=1 "$BINDIR/dev" archive-repo brokenproject >/dev/null 2>&1; then fail "a failed push should exit non-zero" fi -expect "a failed push doesn't archive the repo on GitHub" "" "$(cat "$STUB_GH_LOG")" expect "a failed push still cleans up the temporary clone" "0" "$(count_temp_entries)" -finish "mirrored and archived to the right places, and cleans up after a failure" +finish "mirrored to the right place, and cleans up after a failure" diff --git a/tests/test-aws-login.sh b/tests/test-aws-login.sh index daac170..114cb9a 100755 --- a/tests/test-aws-login.sh +++ b/tests/test-aws-login.sh @@ -2,7 +2,8 @@ set -euo pipefail IFS=$'\n\t' -# dev-aws-login only picks a profile, but getting that wrong logs you into the wrong AWS account. +# dev-aws-login only hands its arguments to aws-vault, but getting that wrong logs you into the +# wrong AWS account. BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" # shellcheck source=tests/helpers.sh @@ -16,17 +17,7 @@ set -euo pipefail echo "$*" STUB -expect "no arguments uses the default profile" \ - "login -- devsoc" "$( - unset AWS_VAULT_PROFILE - "$BINDIR/dev" aws-login - )" +expect "the profile is passed through to aws-vault" \ + "login -- someprofile" "$("$BINDIR/dev" aws-login someprofile)" -expect "AWS_VAULT_PROFILE overrides the default" \ - "login -- someotherprofile" "$(AWS_VAULT_PROFILE=someotherprofile "$BINDIR/dev" aws-login)" - -expect "an explicit profile wins over everything" \ - "login -- explicitprofile" \ - "$(AWS_VAULT_PROFILE=someotherprofile "$BINDIR/dev" aws-login explicitprofile)" - -finish "the right aws-vault profile is chosen" +finish "the profile reaches aws-vault untouched" diff --git a/tests/test-clean-branches.sh b/tests/test-clean-branches.sh index 646825c..becdb54 100755 --- a/tests/test-clean-branches.sh +++ b/tests/test-clean-branches.sh @@ -2,9 +2,8 @@ set -euo pipefail IFS=$'\n\t' -# Checks that dev-clean-branches deletes merged and squash-merged branches while leaving -# unmerged and protected ones alone. Squash-merge detection is the only non-obvious logic in -# these tools, and it silently does nothing when it breaks. +# Checks that dev-clean-branches deletes merged branches while leaving unmerged and protected +# ones alone, and that a repo with nothing to delete says so rather than falling over. CLEAN_BRANCHES="$(cd "$(dirname "$0")/../bin" && pwd)/dev-clean-branches" # shellcheck source=tests/helpers.sh @@ -29,13 +28,6 @@ echo "merged" >merged.txt git add merged.txt git commit --quiet -m "Merged work" -git switch --quiet -c squashed-branch main -echo "squashed one" >squashed.txt -git add squashed.txt -git commit --quiet -m "Squashed work, part one" -echo "squashed two" >>squashed.txt -git commit --quiet -am "Squashed work, part two" - git switch --quiet -c unmerged-branch main echo "unmerged" >unmerged.txt git add unmerged.txt @@ -43,21 +35,18 @@ git commit --quiet -m "Unmerged work" git switch --quiet main git merge --quiet --no-ff -m "Merge merged-branch" merged-branch >/dev/null -git merge --quiet --squash squashed-branch >/dev/null 2>&1 -git commit --quiet -m "Squash merge of squashed-branch" git push --quiet origin main printf '\n' | "$CLEAN_BRANCHES" >/dev/null -expect "merged and squash-merged branches go, the unmerged one stays" \ +expect "the merged branch goes, the unmerged one stays" \ "main unmerged-branch " "$(git branch --format "%(refname:short)" | sort | tr '\n' ' ')" # A second run has nothing to delete, which used to abort the script when grep found no matches. -git switch --quiet main git branch --quiet -D unmerged-branch SECOND_RUN=$(printf '\n' | "$CLEAN_BRANCHES") expect_contains "expected a clean repo to report nothing to remove" \ "$SECOND_RUN" "No local branches need removing" -finish "merged and squash-merged branches removed, and a clean repo says so" +finish "merged branches removed, protected ones kept, and a clean repo says so" diff --git a/tests/test-clone.sh b/tests/test-clone.sh index 1d6ec80..00a1256 100755 --- a/tests/test-clone.sh +++ b/tests/test-clone.sh @@ -2,9 +2,9 @@ set -euo pipefail IFS=$'\n\t' -# dev-clone works out the repo URL, whether the project needs a virtualenv, and which Python to -# build it with. All of that is easy to break silently, so it runs here against stubbed git, -# pyenv and virtualenvwrapper - no network, no real virtualenvs. +# dev-clone works out the repo URL and which Python to build the virtualenv with. Both are easy +# to break silently, so they run here against stubbed git, pyenv and virtualenvwrapper - no +# network, no real virtualenvs. BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" REAL_GIT=$(command -v git) @@ -13,11 +13,10 @@ source "$(dirname "$0")/helpers.sh" make_workdir -mkdir -p "$WORKDIR/fixtures/empty" "$WORKDIR/fixtures/python" "$WORKDIR/fixtures/toxini" \ +mkdir -p "$WORKDIR/fixtures/plain" "$WORKDIR/fixtures/toxini" \ "$WORKDIR/projects" "$WORKDIR/virtualenvs" -touch "$WORKDIR/fixtures/empty/README.md" -touch "$WORKDIR/fixtures/python/pyproject.toml" +touch "$WORKDIR/fixtures/plain/README.md" printf '[testenv]\nbasepython = python3.11\n' >"$WORKDIR/fixtures/toxini/tox.ini" write_stub git </dev/null } -mkproject_args() { - if [ -f "$STUB_MKPROJECT_ARGS" ]; then - cat "$STUB_MKPROJECT_ARGS" - else - echo "no mkproject" - fi -} - -run_clone empty someproject +run_clone plain someproject expect "a bare name is assumed to be a developersociety repo" \ "git@github.com:developersociety/someproject.git" "$(cat "$STUB_CLONE_URI")" -expect "a project with no Python files gets no virtualenv" "no mkproject" "$(mkproject_args)" +expect "a repo without a tox.ini gets a plain virtualenv" \ + "--force someproject" "$(cat "$STUB_MKPROJECT_ARGS")" -run_clone empty someorg/otherproject +run_clone plain someorg/otherproject expect "an org/repo argument is used as given" \ "git@github.com:someorg/otherproject.git" "$(cat "$STUB_CLONE_URI")" -run_clone empty https://github.com/someorg/urlproject -expect "a browser URL is turned into an SSH remote" \ - "git@github.com:someorg/urlproject.git" "$(cat "$STUB_CLONE_URI")" - -run_clone python pythonproject -expect "a project with a pyproject.toml gets a virtualenv" \ - "--force pythonproject" "$(mkproject_args)" - run_clone toxini toxproject expect "tox.ini's basepython picks the interpreter" \ - "--force --python=/fake/bin/python toxproject" "$(mkproject_args)" - -# The workspace points at the virtualenv's interpreter, so it has to exist by the time it's read. -mkdir -p "$WORKON_HOME/codeproject/bin" -printf '#!/bin/sh\n' >"$WORKON_HOME/codeproject/bin/python" -chmod +x "$WORKON_HOME/codeproject/bin/python" - -run_clone python --vscode codeproject -WORKSPACE_FILE="$PROJECT_HOME/codeproject/codeproject.code-workspace" - -if [ ! -f "$WORKSPACE_FILE" ]; then - fail "--vscode didn't write a workspace file" -else - expect "the workspace points at the project's interpreter" \ - "1" "$(grep -c "$WORKON_HOME/codeproject/bin/python" "$WORKSPACE_FILE")" - expect "the workspace file is hidden from git" \ - "1" "$(grep -c "codeproject.code-workspace" "$PROJECT_HOME/codeproject/.git/info/exclude")" -fi - -run_clone python plainproject -if [ -f "$PROJECT_HOME/plainproject/plainproject.code-workspace" ]; then - fail "a workspace file was written without --vscode" -fi + "--force --python=python3.11 toxproject" "$(cat "$STUB_MKPROJECT_ARGS")" if "$BINDIR/dev" clone someproject >/dev/null 2>&1; then fail "cloning into an existing directory should exit non-zero" fi -finish "repo names, Python detection and the VS Code workspace all behave" +finish "repo names and the tox.ini Python version both behave" diff --git a/tests/test-tofu.sh b/tests/test-tofu.sh index 1afb08e..aa57156 100755 --- a/tests/test-tofu.sh +++ b/tests/test-tofu.sh @@ -2,10 +2,8 @@ set -euo pipefail IFS=$'\n\t' -# "dev tofu env" picks env vars out of the tofu state by name and has to leave alone the -# random_password resources tofu uses internally, and setting one has to remove it from the state -# before re-importing it. "dev tofu all" has to visit every project directory. Runs against a -# stubbed aws-vault, so no AWS credentials are involved. +# dev-tofu runs tofu under a specific AWS profile. The profile is the part worth pinning down, +# since the wrong one points tofu at the wrong account. Runs against a stubbed aws-vault. BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" # shellcheck source=tests/helpers.sh @@ -13,96 +11,17 @@ source "$(dirname "$0")/helpers.sh" make_workdir -cat >"$WORKDIR/state.json" <<'JSON' -{ - "values": { - "root_module": { - "resources": [ - {"type": "random_password", "name": "SENTRY_AUTH_TOKEN", - "values": {"result": "sentry-secret"}}, - {"type": "random_password", "name": "GEOAPIFY_API_KEY", - "values": {"result": "geoapify-secret"}}, - {"type": "random_password", "name": "db_admin_password", - "values": {"result": "internal-secret"}}, - {"type": "aws_instance", "name": "SOMETHING_ELSE", "values": {"result": "not-a-var"}} - ] - } - } -} -JSON - write_stub aws-vault <<'STUB' #!/usr/bin/env bash set -euo pipefail - -# Called as: aws-vault exec PROFILE -- tofu -shift 3 -echo "$* [$(basename "$PWD")]" >> "$STUB_TOFU_LOG" - -case "${2:-}" in - show) - cat "$STUB_STATE_JSON" - ;; - state) - # Only the variables named in $STUB_EXISTING_VARS are already in the state. - if [ "${3:-}" = "list" ]; then - for existing in ${STUB_EXISTING_VARS:-}; do - if [ "random_password.$existing" = "${4:-}" ]; then - echo "${4:-}" - fi - done - fi - ;; -esac +echo "$*" STUB -export STUB_STATE_JSON="$WORKDIR/state.json" -export STUB_TOFU_LOG="$WORKDIR/tofu.log" -export STUB_EXISTING_VARS="" - -# An initialised directory, so the tools don't try to run "tofu init". -mkdir -p "$WORKDIR/project/.terraform" -cd "$WORKDIR/project" - -expect "only upper case variables are listed" \ - $'SENTRY_AUTH_TOKEN=sentry-secret\nGEOAPIFY_API_KEY=geoapify-secret' \ - "$("$BINDIR/dev" tofu env)" - -expect "a single variable can be fetched" \ - "geoapify-secret" "$("$BINDIR/dev" tofu env GEOAPIFY_API_KEY)" - -if "$BINDIR/dev" tofu env NO_SUCH_VARIABLE >/dev/null 2>&1; then - fail "asking for a missing env var should exit non-zero" -fi - -if "$BINDIR/dev" tofu env db_admin_password >/dev/null 2>&1; then - fail "tofu's internal passwords shouldn't be reachable as env vars" -fi - -# Replacing a variable which is already in the state has to remove it before importing. -: >"$STUB_TOFU_LOG" -STUB_EXISTING_VARS="SENTRY_AUTH_TOKEN" \ - "$BINDIR/dev" tofu env set SENTRY_AUTH_TOKEN new-value >/dev/null -expect "replacing a variable removes it from the state, then imports it" \ - $'tofu state rm random_password.SENTRY_AUTH_TOKEN\ntofu import random_password.SENTRY_AUTH_TOKEN new-value' \ - "$(grep -E "state rm|import" "$STUB_TOFU_LOG" | sed -e 's/ \[.*\]$//')" - -# A variable which isn't in the state yet is imported without a pointless removal. -: >"$STUB_TOFU_LOG" -"$BINDIR/dev" tofu env set BRAND_NEW_TOKEN new-value >/dev/null -expect "a brand new variable is imported without a state removal" \ - "tofu import random_password.BRAND_NEW_TOKEN new-value" \ - "$(grep -E "state rm|import" "$STUB_TOFU_LOG" | sed -e 's/ \[.*\]$//')" - -# "all" visits directories holding a tofu.tf, and nothing else. -mkdir -p "$WORKDIR/repo/alpha/.terraform" "$WORKDIR/repo/beta/.terraform" "$WORKDIR/repo/modules" -touch "$WORKDIR/repo/alpha/tofu.tf" "$WORKDIR/repo/beta/tofu.tf" -cd "$WORKDIR/repo" +expect "tofu runs under the devsoc-tofu profile" \ + "exec devsoc-tofu -- tofu plan" "$("$BINDIR/dev" tofu plan)" -: >"$STUB_TOFU_LOG" -"$BINDIR/dev" tofu all plan >/dev/null -expect "every project directory is visited, and nothing else" \ - $'tofu plan [alpha]\ntofu plan [beta]' \ - "$(cat "$STUB_TOFU_LOG")" +expect "tofu's own arguments are passed through untouched" \ + "exec devsoc-tofu -- tofu apply -auto-approve" \ + "$("$BINDIR/dev" tofu apply -auto-approve)" -finish "env vars listed, fetched and imported, and 'all' visits every project" +finish "tofu runs under the right profile, with its arguments intact" diff --git a/tests/test-unlock-server.sh b/tests/test-unlock-server.sh index ce2d0b2..1ea3d14 100755 --- a/tests/test-unlock-server.sh +++ b/tests/test-unlock-server.sh @@ -2,8 +2,8 @@ set -euo pipefail IFS=$'\n\t' -# dev-unlock-server hands a passphrase to a server's initramfs and then waits for it to boot. -# Runs against stubbed op, ssh and sleep, so nothing is contacted and nothing actually waits. +# dev-unlock-server reads a passphrase from 1Password and hands it to a server's initramfs. Runs +# against stubbed op and ssh, so nothing is contacted and no real passphrase is involved. BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" # shellcheck source=tests/helpers.sh @@ -15,7 +15,6 @@ write_stub op <<'STUB' #!/usr/bin/env bash set -euo pipefail case "${1:-}" in - account) [ -z "${STUB_OP_SIGNED_OUT:-}" ] ;; read) echo "$2" >> "$STUB_OP_LOG" echo "passphrase-for-$2" @@ -30,48 +29,26 @@ set -euo pipefail command="${*: -1}" target="${*: -2:1}" -if [ "$command" = "cryptroot-unlock" ]; then - read -r passphrase || true - echo "unlock $target $passphrase" >> "$STUB_SSH_LOG" - exit 0 -fi - -echo "boot-check $target" >> "$STUB_SSH_LOG" -case " ${STUB_UP_HOSTS:-} " in - *" $target "*) exit 0 ;; -esac -exit 1 -STUB - -write_stub sleep <<'STUB' -#!/usr/bin/env bash -exit 0 +read -r passphrase || true +echo "$command $target $passphrase" >> "$STUB_SSH_LOG" STUB export STUB_OP_LOG="$WORKDIR/op.log" export STUB_SSH_LOG="$WORKDIR/ssh.log" -if STUB_OP_SIGNED_OUT=1 "$BINDIR/dev" unlock-server one.example >/dev/null 2>&1; then - fail "being signed out of 1Password should exit non-zero" +if "$BINDIR/dev" unlock-server >/dev/null 2>&1; then + fail "calling it without a hostname should exit non-zero" fi : >"$STUB_OP_LOG" : >"$STUB_SSH_LOG" -STUB_UP_HOSTS="one.example two.example" \ - "$BINDIR/dev" unlock-server one.example two.example >/dev/null +"$BINDIR/dev" unlock-server one.example >/dev/null -expect "each host's passphrase is read from its own 1Password item" \ - $'op://aizi3l3vxjc52mboshwj7bbytq/one.example/password\nop://aizi3l3vxjc52mboshwj7bbytq/two.example/password' \ - "$(cat "$STUB_OP_LOG")" +expect "the passphrase is read from the host's own 1Password item" \ + "op://aizi3l3vxjc52mboshwj7bbytq/one.example/password" "$(cat "$STUB_OP_LOG")" -expect "each host is unlocked as root and then checked for boot, in order" \ - $'unlock root@one.example passphrase-for-op://aizi3l3vxjc52mboshwj7bbytq/one.example/password\nboot-check one.example\nunlock root@two.example passphrase-for-op://aizi3l3vxjc52mboshwj7bbytq/two.example/password\nboot-check two.example' \ +expect "the passphrase is piped to cryptroot-unlock as root" \ + "cryptroot-unlock root@one.example passphrase-for-op://aizi3l3vxjc52mboshwj7bbytq/one.example/password" \ "$(cat "$STUB_SSH_LOG")" -OUTPUT=$(DEV_UNLOCK_TIMEOUT=1 STUB_UP_HOSTS="" \ - "$BINDIR/dev" unlock-server slow.example 2>&1 >/dev/null) - -expect_contains "a host which never boots should warn on stderr" \ - "$OUTPUT" "did not come back" - -finish "passphrases fetched per host, unlocked in order, and slow servers warn" +finish "the passphrase is fetched for the right host and piped to cryptroot-unlock" diff --git a/tests/test-update-aws-config.sh b/tests/test-update-aws-config.sh index ced0b9f..e06b870 100755 --- a/tests/test-update-aws-config.sh +++ b/tests/test-update-aws-config.sh @@ -2,8 +2,8 @@ set -euo pipefail IFS=$'\n\t' -# dev-update-aws-config replaces a file people depend on, so the parts worth checking are that it -# leaves an unchanged config alone, backs up before replacing, and doesn't hoard backups forever. +# dev-update-aws-config replaces a file people depend on, so the parts worth checking are that the +# username reaches the template and that an existing config is moved aside rather than lost. # Runs against a stubbed 1Password CLI. BINDIR="$(cd "$(dirname "$0")/../bin" && pwd)" @@ -16,7 +16,6 @@ write_stub op <<'STUB' #!/usr/bin/env bash set -euo pipefail case "${1:-}" in - account) exit 0 ;; read) cat "$STUB_OP_TEMPLATE" ;; *) exit 1 ;; esac @@ -33,36 +32,19 @@ count_backups() { find "$HOME/.aws" -name "config.old.*" | wc -l | tr -d ' ' } -printf '\n' | "$BINDIR/dev" update-aws-config alice >/dev/null +if "$BINDIR/dev" update-aws-config >/dev/null 2>&1; then + fail "calling it without a username should exit non-zero" +fi + +"$BINDIR/dev" update-aws-config alice >/dev/null expect "the username is substituted into the template" \ "[profile alice]" "$(head -n 1 "$CONFIG_FILE")" expect "the first run leaves no backup behind" "0" "$(count_backups)" -printf '\n' | "$BINDIR/dev" update-aws-config alice >/dev/null -expect "re-running with no changes doesn't write a backup" "0" "$(count_backups)" - -printf '\n' | "$BINDIR/dev" update-aws-config bob >/dev/null -expect "a changed config is written" "[profile bob]" "$(head -n 1 "$CONFIG_FILE")" -expect "replacing the config backs up the old one" "1" "$(count_backups)" - -# Six older backups plus the one above is over the limit, so the oldest should be dropped. -for index in 1 2 3 4 5 6; do - touch "$HOME/.aws/config.old.2020010${index}T000000Z" -done - -printf '\n' | "$BINDIR/dev" update-aws-config carol >/dev/null -expect "old backups are pruned" "5" "$(count_backups)" - -if [ -f "$HOME/.aws/config.old.20200101T000000Z" ]; then - fail "the oldest backup should have been pruned first" -fi - -# A failure reading the template must not leave the config missing or empty. -rm -f "$STUB_OP_TEMPLATE" -if printf '\n' | "$BINDIR/dev" update-aws-config dave >/dev/null 2>&1; then - fail "a failed 'op read' should exit non-zero" -fi -expect "a failed run leaves the existing config in place" \ - "[profile carol]" "$(head -n 1 "$CONFIG_FILE")" +"$BINDIR/dev" update-aws-config bob >/dev/null +expect "the new config is written" "[profile bob]" "$(head -n 1 "$CONFIG_FILE")" +expect "the previous config is moved aside, not overwritten" "1" "$(count_backups)" +expect "the backup holds the config it replaced" \ + "[profile alice]" "$(head -n 1 "$HOME"/.aws/config.old.*)" -finish "config diffed, backed up and pruned, and survives a failed template read" +finish "the username reaches the template, and the old config is kept" diff --git a/tests/test-wipeenv.sh b/tests/test-wipeenv.sh index 39901e7..ec2b80a 100755 --- a/tests/test-wipeenv.sh +++ b/tests/test-wipeenv.sh @@ -27,12 +27,12 @@ export STUB_PIP_UNINSTALLED="$WORKDIR/uninstalled" expect "running outside a virtualenv explains itself" "Must be in a virtual env" \ "$( unset VIRTUAL_ENV - printf '\n' | "$BINDIR/dev" wipeenv 2>&1 || true + "$BINDIR/dev" wipeenv 2>&1 || true )" if ( unset VIRTUAL_ENV - printf '\n' | "$BINDIR/dev" wipeenv >/dev/null 2>&1 + "$BINDIR/dev" wipeenv >/dev/null 2>&1 ); then fail "running outside a virtualenv should exit non-zero" fi @@ -48,7 +48,7 @@ requests==2.32 PACKAGES rm -f "$STUB_PIP_UNINSTALLED" -printf '\n' | "$BINDIR/dev" wipeenv >/dev/null +"$BINDIR/dev" wipeenv >/dev/null expect "pip, setuptools and wheel are left alone" \ "django==5.2 requests==2.32" "$(cat "$STUB_PIP_UNINSTALLED")" @@ -57,12 +57,7 @@ pip==25.0 setuptools==80.0 PACKAGES -rm -f "$STUB_PIP_UNINSTALLED" expect "an already-empty virtualenv says there's nothing to do" "Nothing to remove" \ - "$(printf '\n' | "$BINDIR/dev" wipeenv)" - -if [ -f "$STUB_PIP_UNINSTALLED" ]; then - fail "nothing should have been uninstalled from an empty virtualenv" -fi + "$("$BINDIR/dev" wipeenv 2>/dev/null)" finish "refuses to run outside a virtualenv, and never uninstalls pip"