ba-auto-daily/clean_scratchpad.sh
Nik Afiq 634d77d9d2 feat(clean_scratchpad): implement script for safe deletion of temporary files in scratchpad directory
fix(arena): resolve consecutive-invocation navigation issue by ensuring return to home before opening Tactical Challenge
docs(mapping): update Arena task description with navigation bug fix details
2026-07-11 00:20:04 +09:00

54 lines
1.8 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# Deletes files directly inside this repo's scratchpad/ directory that match
# the given filename patterns. Hard-guarded to never operate outside
# scratchpad/, regardless of what patterns are passed in.
#
# Usage:
# ./clean_scratchpad.sh '*.png' '*.log' 'probe_ocr_now.py'
#
# Each argument is a filename pattern (matched via `find -name` against
# files directly inside scratchpad/, not subdirectories) or an exact
# filename. No argument may contain a path separator or "..", so a pattern
# can never reach outside scratchpad/.
if [[ $# -eq 0 ]]; then
echo "Usage: $0 PATTERN [PATTERN...]" >&2
echo "Example: $0 '*.png' '*.log' 'probe_ocr_now.py'" >&2
exit 1
fi
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
TARGET_DIR="$SCRIPT_DIR/scratchpad"
if [[ "$(basename -- "$TARGET_DIR")" != "scratchpad" ]]; then
echo "Refusing to run: target is not named 'scratchpad' ($TARGET_DIR)" >&2
exit 1
fi
if [[ ! -d "$TARGET_DIR" ]]; then
echo "Refusing to run: $TARGET_DIR does not exist or is not a directory" >&2
exit 1
fi
RESOLVED_TARGET="$(cd "$TARGET_DIR" && pwd -P)"
if [[ "$RESOLVED_TARGET" != "$SCRIPT_DIR/scratchpad" ]]; then
echo "Refusing to run: scratchpad resolves outside the expected location ($RESOLVED_TARGET)" >&2
exit 1
fi
deleted_count=0
for pattern in "$@"; do
if [[ "$pattern" == */* || "$pattern" == *..* || -z "$pattern" ]]; then
echo "Refusing pattern '$pattern': patterns must be plain filenames/globs, no paths" >&2
exit 1
fi
while IFS= read -r -d '' file; do
echo "deleting: $file"
rm -f -- "$file"
deleted_count=$((deleted_count + 1))
done < <(find "$RESOLVED_TARGET" -maxdepth 1 -type f -name "$pattern" -print0)
done
echo "Deleted $deleted_count file(s) from $RESOLVED_TARGET"