#!/usr/bin/env bash set -euo pipefail TARGET_REPO="${1:-$(pwd)}" ALLOWED_PREFIX="${2:-.secrets/}" TAG="${3:-[check-no-tracked-dotenv]}" ALLOWLIST_FILE="${4:-}" if [[ ! -d "${TARGET_REPO}/.git" ]]; then echo "${TAG} ERR not a git repository: ${TARGET_REPO}" >&2 exit 1 fi tracked_dotenv="$( git -C "$TARGET_REPO" ls-files | awk -v allowed="$ALLOWED_PREFIX" ' /(^|\/)(\.env($|\.|\/)|[^\/]+\.env($|\/))/ { if ($0 !~ ("^" allowed)) print } ' )" if [[ -n "$ALLOWLIST_FILE" && -f "$ALLOWLIST_FILE" ]]; then filtered_dotenv="" while IFS= read -r dotenv_path; do [[ -z "$dotenv_path" ]] && continue allowed_match=0 while IFS= read -r allowed_path; do allowed_trimmed="$(printf '%s' "$allowed_path" | awk '{$1=$1;print}')" [[ -z "$allowed_trimmed" ]] && continue [[ "$allowed_trimmed" == \#* ]] && continue if [[ "$dotenv_path" == "$allowed_trimmed" ]]; then allowed_match=1 break fi done < "$ALLOWLIST_FILE" if [[ "$allowed_match" -eq 0 ]]; then filtered_dotenv+="${dotenv_path}"$'\n' fi done <<< "$tracked_dotenv" tracked_dotenv="${filtered_dotenv%$'\n'}" fi if [[ -n "$tracked_dotenv" ]]; then echo "${TAG} ERR tracked .env files are forbidden outside ${ALLOWED_PREFIX}" >&2 printf '%s\n' "$tracked_dotenv" >&2 exit 1 fi echo "${TAG} OK"