pantheon/bin/consolidate
2025-02-06 19:26:36 +08:00

89 lines
No EOL
2.5 KiB
Bash
Executable file

#!/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
# 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
if [[ "$(basename "$entry")" != ".gitignore" ]] &&
! is_ignored "$entry" &&
[[ "$entry" =~ $pattern ]]; then # Check if file matches regex
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