Skip to content

Instantly share code, notes, and snippets.

@AJV009
Created November 8, 2024 07:32
Show Gist options
  • Select an option

  • Save AJV009/20fe39441988fccddc1080ee55ef0271 to your computer and use it in GitHub Desktop.

Select an option

Save AJV009/20fe39441988fccddc1080ee55ef0271 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Check if source directory is provided
if [ "$#" -lt 1 ]; then
echo "Usage: $0 source_directory [output_directory]"
echo "Example: $0 /path/to/source"
echo "If output_directory is not specified, will create '{source_directory}_flattened'"
exit 1
fi
# Get source directory
source_dir="$1"
# Set output directory - either from argument or default
if [ "$#" -eq 2 ]; then
output_dir="$2"
else
output_dir="${source_dir%/}_flattened"
fi
# Create output directory if it doesn't exist
mkdir -p "$output_dir"
# Function to add comment based on file type
add_comment() {
local file="$1"
local output_file="$2"
local filepath="${file#$source_dir/}" # Get relative path from source_dir
local comment_line
# Determine comment style based on file extension
case "${file,,}" in # Convert to lowercase for matching
*.py)
comment_line="# filename: $filepath"
;;
*.ts|*.tsx|*.css)
comment_line="// filename: $filepath"
;;
*.txt|*.md)
comment_line="<!-- filename: $filepath -->"
;;
*dockerfile*)
comment_line="# filename: $filepath"
;;
*)
comment_line="// filename: $filepath"
;;
esac
# Create new file with comment and content
echo "$comment_line" > "$output_file"
cat "$file" >> "$output_file"
echo "Processed: $filepath -> $(basename "$output_file")"
}
# Find and process files
find "$source_dir" \
-type f \
\( -name "*.txt" -o -name "*.md" -o -name "*.py" -o -name "Dockerfile" \
-o -name "*.ts" -o -name "*.tsx" -o -name "*.css" \) \
-not -path "*/\.*" \
-not -path "*/.github/*" \
-not -path "*/.vscode/*" \
-not -path "*/client/node_modules/*" \
-not -path "*/node_modules/*" \
| while read -r file; do
filename=$(basename "$file")
output_file="$output_dir/$filename"
# Handle duplicate filenames by adding a counter
counter=1
while [ -f "$output_file" ]; do
base="${filename%.*}"
ext="${filename##*.}"
output_file="$output_dir/${base}_${counter}.${ext}"
((counter++))
done
add_comment "$file" "$output_file"
done
echo "Done! Files have been processed and placed in: $output_dir"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment