Created
June 27, 2024 13:31
-
-
Save treyhoover/84c5bcddc6077479074761181012b3a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Set default values for directory and pattern | |
directory="." | |
pattern="*.ts,*.tsx,*.js,*.jsx" | |
# Override defaults with arguments if provided | |
if [ $# -ge 1 ]; then | |
directory="$1" | |
fi | |
if [ $# -ge 2 ]; then | |
pattern="$2" | |
fi | |
# Create a temporary directory with a random name | |
tmp_dir=$(mktemp -d -t concatenate_output.XXXXXX) | |
output_file="$tmp_dir/output.txt" | |
# Function to recursively find and concatenate files | |
concatenate_files() { | |
local dir="$1" | |
local patterns="$2" | |
# Check if the directory is inside a Git repository | |
if git -C "$dir" rev-parse --is-inside-work-tree >/dev/null 2>&1; then | |
echo "Inside a Git repository. Ignoring gitignored files." | |
# Use git ls-files to get the list of files not ignored by git | |
local files | |
files=$(git -C "$dir" ls-files --cached --others --exclude-standard | grep -E "$(echo "$patterns" | sed 's/,/|/g' | sed 's/\./\\./g' | sed 's/\*/.*/g')") | |
for file in $files; do | |
echo "Processing $file" | |
echo "===== $file =====" >> "$output_file" | |
cat "$dir/$file" >> "$output_file" | |
echo "" >> "$output_file" | |
done | |
else | |
echo "Not inside a Git repository or no gitignored files found." | |
# Convert comma-separated patterns to -o format for find | |
local find_patterns=() | |
IFS=',' read -ra ADDR <<< "$patterns" | |
for i in "${ADDR[@]}"; do | |
find_patterns+=(-name "$i" -o) | |
done | |
# Remove the last -o | |
unset 'find_patterns[${#find_patterns[@]}-1]' | |
# Find all files matching the glob patterns | |
find "$dir" -type f \( "${find_patterns[@]}" \) | while read -r file; do | |
echo "Processing $file" | |
echo "===== $file =====" >> "$output_file" | |
cat "$file" >> "$output_file" | |
echo "" >> "$output_file" | |
done | |
fi | |
} | |
# Run the function | |
concatenate_files "$directory" "$pattern" | |
# Pipe the output file to pbcopy if it exists | |
if [[ -f "$output_file" ]]; then | |
cat "$output_file" | pbcopy | |
echo "All files have been concatenated into $output_file and copied to clipboard" | |
else | |
echo "No files were found or concatenated." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment