Skip to content

Instantly share code, notes, and snippets.

@nilium
Created January 10, 2020 23:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilium/6d5ba929fca4935d30800440a0add447 to your computer and use it in GitHub Desktop.
Save nilium/6d5ba929fca4935d30800440a0add447 to your computer and use it in GitHub Desktop.
Script to run a shell or command in a clean, temporary copy of a repository.
#!/usr/bin/env bash
# cleanroom: run a command or shell in a clean, temporary copy of a repository.
case "$1" in
-h|-help|--help)
cat <<'USAGE'
Usage: cleanroom [-h|-help|--help] [CMD...]
Execute a command in a clone of the current repository, made under
a temporary directory.
If no command is given, it runs the current shell in interactive mode.
USAGE
exit 2
;;
esac
quiet() {
"$@" >/dev/null 2>&1
}
dir="$(pwd)"
top="$(git rev-parse --show-toplevel)"
subdir="${dir#${top}}"
subdir="${subdir#/}"
if ! tempdir="$(mktemp -d)"; then
exit 1
fi
trap 'rm -rf "${tempdir}"' EXIT
set -e
quiet git clone --reference "${top}" "${top}" "${tempdir}"
quiet cp "${top}/.git/config" "${tempdir}/.git/config"
quiet cd "${tempdir}${subdir:+/$subdir}"
if [ $# -eq 0 ]; then
"$SHELL" -i
else
cmd="$1"
shift
cmdline="$(printf '%q' "$cmd")"
if [ $# -gt 0 ]; then
cmdline+="$(printf ' %q' "$@")"
fi
"$SHELL" -ic "$cmdline" cleanroom-script
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment