nix-gitlab-ci/lib/impl/sandbox_helper.sh
technofab f5181b7b61
fix(sandbox_helper): fix comparisons, rename TMPDIR variable, add help
1. fixes comparisons with true for flag variables
2. renames TMPDIR to NGCI_TMPDIR so it doesn't interfere with the
   standardized TMPDIR var (and at some point accidentally deleting /tmp)
3. add small help message when invalid arg/param is passed
4. run `git add .` on copied git repo in /tmp so staged files stay
   staged there aswell
2025-11-13 21:40:24 +01:00

75 lines
1.7 KiB
Bash

echo -e "\e[32mSetting up...\e[0m"
actualJobScript=$1
shift
INCLUDE_DIRTY=false
NO_SANDBOX=false
KEEP_TMP=false
KEEP_ENV=""
# parse flags
while [[ $# -gt 0 ]]; do
case "$1" in
--include-dirty)
INCLUDE_DIRTY=true
shift
;;
--no-sandbox)
NO_SANDBOX=true
shift
;;
--keep-tmp)
KEEP_TMP=true
shift
;;
--keep-env)
KEEP_ENV="$2"
shift 2
;;
*)
echo "Unknown option: $1" >&2
echo "use --include-dirty, --no-sandbox, --keep-tmp and --keep-env <ENV>" >&2
exit 1
;;
esac
done
if [ $NO_SANDBOX = false ]; then
echo "Running with simple sandboxing"
NGCI_TMPDIR=$(mktemp -dt "nix-gitlab-ci.XXX")
if [ $KEEP_TMP = false ]; then
trap "rm -rf '$NGCI_TMPDIR'" EXIT
else
echo "Temp dir will be preserved at: $NGCI_TMPDIR"
fi
# check if dirty
DIRTY_PATCH=""
if ! git diff --quiet && ! git diff --staged --quiet; then
echo "Warning: working tree is dirty."
DIRTY_PATCH=$(mktemp -t "nix-gitlab-ci.XXX.patch")
git diff --staged > "$DIRTY_PATCH"
trap "rm -f '$DIRTY_PATCH'" EXIT
fi
git clone . $NGCI_TMPDIR
pushd $NGCI_TMPDIR >/dev/null
if [[ ! -z "$DIRTY_PATCH" && $INCLUDE_DIRTY = true ]]; then
echo "Copying dirty changes..."
git apply "$DIRTY_PATCH" 2>/dev/null || echo "Failed to copy dirty changes"
git add . # required so the files are staged again
fi
echo "Running job in $NGCI_TMPDIR"
env -i $(
if [[ -n "$KEEP_ENV" ]]; then
IFS=',' read -ra VARS <<< "$KEEP_ENV"
for var in "${VARS[@]}"; do
printf '%s=%q ' "$var" "${!var}"
done
fi
) bash $actualJobScript
popd >/dev/null
else
exec $actualJobScript
fi