Merge pull request #1 from bwfiq/feature/consolidate-script

Add repo consolidation script at ~/bin/consolidate. Good work Rafiq
This commit is contained in:
Mohammad Rafiq 2025-02-06 19:53:00 +08:00 committed by GitHub
commit bb75efbdf8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

102
bin/consolidate Executable file
View file

@ -0,0 +1,102 @@
#!/bin/bash
# Functions:
# Get the list of specified file extensions from script arguments
get_extensions() {
if [ $# -gt 0 ]; then
# Create an array for extensions
EXTENSIONS=()
for ext in "$@"; do
# Remove the leading dot if present
ext="${ext#.}"
EXTENSIONS+=("$ext")
done
else
EXTENSIONS=() # No extensions specified, match everything
fi
}
# Get the current date in YYYY-MM-DD format
get_current_date() {
date +%F
}
# Check if a file is ignored according to .gitignore
is_ignored() {
local filepath="$1"
git check-ignore -q "$filepath" # Returns 0 if ignored, 1 otherwise
}
# Process a single file: append its header and content to the output file
process_file() {
local filepath="$1"
{
echo "# $filepath" # File header
echo "" # Blank line
cat "$filepath" # File content
echo "" # Blank line after content
} >> "$output_file"
}
# Recursively traverse directories to find and process files
traverse_directory() {
local dir="$1"
# Construct regex pattern based on provided extensions
if [ ${#EXTENSIONS[@]} -gt 0 ]; then
EXTENSIONS_PATTERN=$(printf '\\|%s' "${EXTENSIONS[@]}")
pattern=".*\.\($EXTENSIONS_PATTERN\)$" # Pattern for matching specified extensions
else
pattern=".*$" # Matches everything if no extensions specified
fi
# Array of filenames to exclude from processing
local EXCLUDED_FILES=("LICENSE" ".gitignore")
# Loop through entries in the specified directory
for entry in "$dir"/*; do
if [[ -e "$entry" ]]; then # Check if the entry exists
if [[ -d "$entry" ]]; then # Process directories
if [[ "$(basename "$entry")" != ".git" ]]; then
traverse_directory "$entry" # Recursive call
fi
elif [[ -f "$entry" ]]; then # Process files
# Check if the file should be excluded
local exclude=false
for excluded in "${EXCLUDED_FILES[@]}"; do
if [[ "$(basename "$entry")" == "$excluded" ]]; then
exclude=true
break
fi
done
# Process the file only if it's not excluded, not ignored, and matches the pattern
if [[ "$exclude" == false ]] &&
! is_ignored "$entry" &&
[[ "$entry" =~ $pattern ]]; then
process_file "$entry" # Process the file
fi
fi
fi
done
}
# Main function to execute the script logic
main() {
get_extensions "$@" # Pass all script arguments to get_extensions function
output_file="output-$(get_current_date).txt" # Define the output file name
# Clear previous output file if it exists
> "$output_file"
# Start the file traversal from the current directory
traverse_directory "."
echo "Consolidation complete! Output saved in: $output_file" # Completion message
}
# Execution begins here
echo "Consolidating..."
main "$@" # Invoke main function with script arguments