diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..e8af333 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,16 @@ +name: test + +on: + push: + pull_request: + +jobs: + check: + 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 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b2eb77f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,101 @@ +# AGENTS.md + +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. + +`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 +`${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. 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 + +`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 +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi +``` + +## Tests + +Plain bash, no framework. One executable `tests/test-.sh` per command, sourcing +`tests/helpers.sh` for its assertions and stub scaffolding. + +- 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 + +The README is deliberately limited to installation and usage. New documentation goes in `docs/`. diff --git a/Formula/devtools.rb b/Formula/devtools.rb new file mode 100644 index 0000000..8c4e121 --- /dev/null +++ b/Formula/devtools.rb @@ -0,0 +1,32 @@ +# 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" + + # 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 + + # 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" + 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 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cd331bd --- /dev/null +++ b/Makefile @@ -0,0 +1,41 @@ +SHELL=/bin/bash +.DEFAULT_GOAL := help + +SHELL_SOURCES = bin/dev* tests/*.sh + + +# ------------------------------- +# 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: + @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 shellcheck shfmt + +check: ## Check for any obvious errors in the project's setup. +check: lint test + +format: ## Run this project's code formatters. +format: + shfmt --indent 4 --write $(SHELL_SOURCES) + +lint: ## Lint the project. +lint: + shellcheck $(SHELL_SOURCES) + shfmt --indent 4 --diff $(SHELL_SOURCES) + +test: ## Run this project's tests. +test: + @for test in tests/test-*.sh; do \ + echo "== $$test"; \ + "$$test" || exit 1; \ + done diff --git a/README.md b/README.md new file mode 100644 index 0000000..2b2c78c --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +# 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. + +To upgrade later: + +```console +$ brew upgrade devtools +``` + +## 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, and is available under its own name, so `dev clone devsoc` and `dev-clone devsoc` do the same thing. + +```console +$ dev help +$ dev help tofu +$ 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 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 + +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. + +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/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. diff --git a/bin/dev b/bin/dev new file mode 100755 index 0000000..16a2f69 --- /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" "$@" diff --git a/bin/dev-archive-repo b/bin/dev-archive-repo index dc7f240..ce8852d 100755 --- a/bin/dev-archive-repo +++ b/bin/dev-archive-repo @@ -1,20 +1,36 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' -if [ $# != 1 ]; then - echo "Must specify repo name to clone" +# help: Mirror a repo to the archive server +# +# Usage: +# dev archive-repo repo +# +# 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 + +ORG="developersociety" +ARCHIVE_HOST="smirkenorff.devsoc.org" + +if [ "$#" -ne 1 ]; then + echo "Usage: dev archive-repo repo" exit 1 fi -GIT_REPO=$1 +REPO_ARG="$1" + +echo "Archiving $REPO_ARG" -echo "Archiving ${GIT_REPO}" +# 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 -TMPDIR=$(mktemp -d) +CLONE_DIR="$WORK_DIR/$REPO_ARG.git" -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" +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 6c76d03..8cf5beb 100755 --- a/bin/dev-aws-login +++ b/bin/dev-aws-login @@ -2,4 +2,15 @@ set -euo pipefail IFS=$'\n\t' +# help: Open the AWS console via aws-vault +# +# Usage: +# dev aws-login +# +# Arguments are passed straight through to "aws-vault login". + +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + exec "$(dirname "$0")/dev" help "${0##*/dev-}" +fi + exec aws-vault login -- "$@" diff --git a/bin/dev-clean-branches b/bin/dev-clean-branches index f7dd0c3..b05a07b 100755 --- a/bin/dev-clean-branches +++ b/bin/dev-clean-branches @@ -1,29 +1,52 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' +# help: Delete merged local branches and prune remotes +# +# Usage: +# dev clean-branches +# +# 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-}" +fi + +PROTECTED_BRANCHES="main master dev" + # 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 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 +# 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 --merged "$DEFAULT_BRANCH" --format "%(refname:short)"); do + case " $PROTECTED_BRANCHES $DEFAULT_BRANCH " in + *" $BRANCH "*) continue ;; + esac + + BRANCHES+=("$BRANCH") +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 + read -r -p "Press Enter to delete the above branches, or -c to bail" - echo "$BRANCHES" | xargs git branch -d + git branch -d "${BRANCHES[@]}" echo "Done." else - echo "No local branches needing" + echo "No local branches need removing" fi echo diff --git a/bin/dev-clone b/bin/dev-clone index ef76701..4d90071 100755 --- a/bin/dev-clone +++ b/bin/dev-clone @@ -1,28 +1,42 @@ -#!/bin/bash +#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' -# shellcheck disable=SC1090 +# help: Clone a repo and set up virtualenvwrapper for it +# +# Usage: +# dev clone [org/]repo +# +# 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-}" +fi + +DEFAULT_ORG="developersociety" + +# shellcheck source=/dev/null # path is set per-machine source "$VIRTUALENVWRAPPER_SCRIPT" -if [ $# != 1 ]; then - echo "Must specify repo name to clone" +if [ "$#" -ne 1 ]; then + echo "Usage: dev clone [org/]repo" exit 1 fi # Handle org/repo, and repo -if [[ $1 == *"/"* ]]; then - REPO_NAME="$1" - PROJECT_NAME="${1##*/}" -else - REPO_NAME="developersociety/$1" - PROJECT_NAME="$1" -fi +REPO_ARG="$1" +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" +# shellcheck disable=SC2153 # PROJECT_HOME is virtualenvwrapper's, not a typo of PROJECT_NAME PROJECT_DIR="$PROJECT_HOME/$PROJECT_NAME" -if [ -a "$PROJECT_DIR" ]; then +if [ -e "$PROJECT_DIR" ]; then echo "Target directory already exists:" echo " $PROJECT_DIR" exit 1 @@ -32,26 +46,28 @@ 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..." -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") +# 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" + VIRTUALENVWRAPPER_VIRTUALENV=$VIRTUALENV_EXE mkproject --force --python="$PYTHON_VERSION" \ + "$PROJECT_NAME" else mkproject --force "$PROJECT_NAME" fi +set -u + echo -echo "Done - to active this project: workon $PROJECT_NAME" +echo "Done - to activate this project: workon $PROJECT_NAME" diff --git a/bin/dev-tofu b/bin/dev-tofu index b2db1f2..d466c6f 100755 --- a/bin/dev-tofu +++ b/bin/dev-tofu @@ -2,4 +2,17 @@ set -euo pipefail IFS=$'\n\t' -exec aws-vault exec devsoc-tofu -- tofu "$@" +# help: Run tofu with the devsoc-tofu AWS profile +# +# Usage: +# dev 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="devsoc-tofu" + +exec aws-vault exec "$PROFILE" -- tofu "$@" diff --git a/bin/dev-unlock-server b/bin/dev-unlock-server index 4be6326..5c3ed55 100755 --- a/bin/dev-unlock-server +++ b/bin/dev-unlock-server @@ -2,15 +2,32 @@ 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 a server +# +# Usage: +# dev unlock-server hostname.devsoc.org +# +# 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-}" +fi + +OP_VAULT="aizi3l3vxjc52mboshwj7bbytq" +KNOWN_HOSTS_FILE="$HOME/.ssh/known_hosts.cryptroot-unlock" + +if [ "$#" -ne 1 ]; then + echo "Usage: dev unlock-server hostname.devsoc.org" >&2 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" \ +LUKS_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 "$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 bd29fcb..e8530e6 100755 --- a/bin/dev-update-aws-config +++ b/bin/dev-update-aws-config @@ -2,21 +2,35 @@ 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 +# +# 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 + +CONFIG_FILE="$HOME/.aws/config" + +if [ "$#" -ne 1 ]; then + echo "Usage: dev update-aws-config username" exit 1 fi CONFIG_USERNAME="$1" -mkdir -p ~/.aws +mkdir -p "$HOME/.aws" -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" +if [ -f "$CONFIG_FILE" ]; then + TIMESTAMP=$(date -u +"%Y%m%dT%H%M%SZ") + echo "Backup of existing config saved to: $CONFIG_FILE.old.$TIMESTAMP" + mv "$CONFIG_FILE" "$CONFIG_FILE.old.$TIMESTAMP" fi -op read "op://Shared/AWS Config Template/notesPlain" | sed -e "s|USERNAME|$CONFIG_USERNAME|g" > ~/.aws/config +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 9994f8a..4f3e1d7 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 +# +# 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,7 @@ 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 +if ! pip list --format=freeze | grep -v "^pip=\|^setuptools=\|^wheel=" | + xargs pip uninstall -y; then echo "Nothing to remove" fi diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..b301bd6 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,65 @@ +# 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). + +## 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/tests/helpers.sh b/tests/helpers.sh new file mode 100644 index 0000000..796b2ce --- /dev/null +++ b/tests/helpers.sh @@ -0,0 +1,56 @@ +# 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 +} + +# 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 +} + +finish() { + if [ "$FAILED" != 0 ]; then + exit 1 + fi + + echo "PASS: $1" +} diff --git a/tests/test-archive-repo.sh b/tests/test-archive-repo.sh new file mode 100755 index 0000000..7a17776 --- /dev/null +++ b/tests/test-archive-repo.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# 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 +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 + +export STUB_GIT_LOG="$WORKDIR/git.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" +"$BINDIR/dev" archive-repo oldproject >/dev/null + +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 temporary clone is cleaned up" "0" "$(count_temp_entries)" + +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 still cleans up the temporary clone" "0" "$(count_temp_entries)" + +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 new file mode 100755 index 0000000..114cb9a --- /dev/null +++ b/tests/test-aws-login.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# 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 +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub aws-vault <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +echo "$*" +STUB + +expect "the profile is passed through to aws-vault" \ + "login -- someprofile" "$("$BINDIR/dev" aws-login someprofile)" + +finish "the profile reaches aws-vault untouched" diff --git a/tests/test-clean-branches.sh b/tests/test-clean-branches.sh new file mode 100755 index 0000000..becdb54 --- /dev/null +++ b/tests/test-clean-branches.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# 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 +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 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 push --quiet origin main + +printf '\n' | "$CLEAN_BRANCHES" >/dev/null + +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 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 branches removed, protected ones kept, and a clean repo says so" diff --git a/tests/test-clone.sh b/tests/test-clone.sh new file mode 100755 index 0000000..00a1256 --- /dev/null +++ b/tests/test-clone.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# 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) +# shellcheck source=tests/helpers.sh +source "$(dirname "$0")/helpers.sh" + +make_workdir + +mkdir -p "$WORKDIR/fixtures/plain" "$WORKDIR/fixtures/toxini" \ + "$WORKDIR/projects" "$WORKDIR/virtualenvs" + +touch "$WORKDIR/fixtures/plain/README.md" +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 +} + +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 repo without a tox.ini gets a plain virtualenv" \ + "--force someproject" "$(cat "$STUB_MKPROJECT_ARGS")" + +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 toxini toxproject +expect "tox.ini's basepython picks the interpreter" \ + "--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 and the tox.ini Python version both behave" diff --git a/tests/test-dev.sh b/tests/test-dev.sh new file mode 100755 index 0000000..5155332 --- /dev/null +++ b/tests/test-dev.sh @@ -0,0 +1,79 @@ +#!/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)" + +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 + 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 + +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" +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") + 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)" + + 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-tofu.sh b/tests/test-tofu.sh new file mode 100755 index 0000000..aa57156 --- /dev/null +++ b/tests/test-tofu.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# 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 +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub aws-vault <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +echo "$*" +STUB + +expect "tofu runs under the devsoc-tofu profile" \ + "exec devsoc-tofu -- tofu plan" "$("$BINDIR/dev" tofu plan)" + +expect "tofu's own arguments are passed through untouched" \ + "exec devsoc-tofu -- tofu apply -auto-approve" \ + "$("$BINDIR/dev" tofu apply -auto-approve)" + +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 new file mode 100755 index 0000000..1ea3d14 --- /dev/null +++ b/tests/test-unlock-server.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +# 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 +source "$(dirname "$0")/helpers.sh" + +make_workdir + +write_stub op <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +case "${1:-}" in + 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}" + +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 "$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" +"$BINDIR/dev" unlock-server one.example >/dev/null + +expect "the passphrase is read from the host's own 1Password item" \ + "op://aizi3l3vxjc52mboshwj7bbytq/one.example/password" "$(cat "$STUB_OP_LOG")" + +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")" + +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 new file mode 100755 index 0000000..e06b870 --- /dev/null +++ b/tests/test-update-aws-config.sh @@ -0,0 +1,50 @@ +#!/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 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)" +# 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 + 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 ' ' +} + +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)" + +"$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 "the username reaches the template, and the old config is kept" diff --git a/tests/test-wipeenv.sh b/tests/test-wipeenv.sh new file mode 100755 index 0000000..ec2b80a --- /dev/null +++ b/tests/test-wipeenv.sh @@ -0,0 +1,63 @@ +#!/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 + "$BINDIR/dev" wipeenv 2>&1 || true + )" + +if ( + unset VIRTUAL_ENV + "$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" +"$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 + +expect "an already-empty virtualenv says there's nothing to do" "Nothing to remove" \ + "$("$BINDIR/dev" wipeenv 2>/dev/null)" + +finish "refuses to run outside a virtualenv, and never uninstalls pip"