Skip to content

Instantly share code, notes, and snippets.

@mwotton
Last active March 24, 2025 07:56
Show Gist options
  • Select an option

  • Save mwotton/bbd198f8ed76c231e0fb0eb644d07fb2 to your computer and use it in GitHub Desktop.

Select an option

Save mwotton/bbd198f8ed76c231e0fb0eb644d07fb2 to your computer and use it in GitHub Desktop.
exe
#!/bin/bash
# exe - Run a command, extract filenames from its output, and generate /add commands.
# The script tries matching by progressively stripping leading directory components.
# Usage: exe <command> [args...]
if [ "$#" -eq 0 ]; then
echo "Usage: $0 <command> [args...]"
exit 1
fi
# Get the repository root.
repo_root=$(git rev-parse --show-toplevel)
if [ -z "$repo_root" ]; then
echo "Not in a git repository."
exit 1
fi
# Create a temporary file to capture command output.
tmpfile=$(mktemp)
trap 'rm -f "$tmpfile"' EXIT
# Run the command, tee its output to the temporary file.
"$@" 2>&1 | tee "$tmpfile"
status=${PIPESTATUS[0]}
# Write the .LOADCOMMANDS file to the repository root.
loadfile="$repo_root/.LOADCOMMANDS"
> "$loadfile" # clear or create it
# For each git-tracked file, try matching using progressively shorter substrings.
git ls-files | while IFS= read -r file; do
path_to_check="$file"
while true; do
# If the current substring is too short, break out to avoid false positives.
if [ ${#path_to_check} -lt 3 ]; then
break
fi
if grep -qF "$path_to_check" "$tmpfile"; then
echo "/add $file" >> "$loadfile"
break
fi
# If no slash remains, there's nothing more to strip.
if [[ "$path_to_check" != */* ]]; then
break
fi
# Remove the first directory component.
path_to_check=$(echo "$path_to_check" | sed 's/^[^\/]*\///')
done
done
exit $status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment