Skip to content

Instantly share code, notes, and snippets.

@tomquirk
Created November 5, 2023 01:02
Show Gist options
  • Save tomquirk/4d6ad610935de7a594266dc543991332 to your computer and use it in GitHub Desktop.
Save tomquirk/4d6ad610935de7a594266dc543991332 to your computer and use it in GitHub Desktop.
Clear stale node modules
#!/bin/bash
# Check if a directory has had a git commit in the last 30 days
hasRecentGitCommit() {
local dir="$1"
cd "$dir" || return 1
local last_commit_date
last_commit_date=$(git log -1 --format="%at")
local current_date
current_date=$(date +%s)
local thirty_days_ago
thirty_days_ago=$((current_date - 2592000)) # 30 days in seconds
[ "$last_commit_date" -ge "$thirty_days_ago" ]
}
# Iterate through subdirectories of the given directory
deleteNodeModules() {
local root_dir="$1"
find "$root_dir" -type d -name "node_modules" | while read -r node_modules_dir; do
local parent_dir
parent_dir=$(dirname "$node_modules_dir")
if ! hasRecentGitCommit "$parent_dir"; then
echo "Deleting $node_modules_dir"
rm -rf "$node_modules_dir"
fi
done
}
# Main script
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory-path>"
exit 1
fi
directory_path="$1"
if [ ! -d "$directory_path" ]; then
echo "Error: Directory not found."
exit 1
fi
deleteNodeModules "$directory_path"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment