Skip to content

Instantly share code, notes, and snippets.

@BrianSigafoos
Created June 29, 2024 17:58
Show Gist options
  • Save BrianSigafoos/39859a22a2f6144ded544d1a39e69220 to your computer and use it in GitHub Desktop.
Save BrianSigafoos/39859a22a2f6144ded544d1a39e69220 to your computer and use it in GitHub Desktop.
Script to gather files
#!/bin/bash
# Usage: script/gather_files <directory_path> [file_extension]
# `script/gather_files app/models` # Gather contents of ALL files in app/models directory
# `script/gather_files app .rb` # Gather contents of all RUBY files in app directory
# Check if directory path is provided
if [ "$#" -lt 1 ]; then
echo "Usage: $0 <directory_path> [file_extension]"
exit 1
fi
DIRECTORY=$1
EXTENSION=$2
# Check if the provided path is a directory
if [ ! -d "$DIRECTORY" ]; then
echo "The directory $DIRECTORY does not exist."
exit 1
fi
# Temporary file to store the output
TEMP_FILE=$(mktemp)
# Function to process the file and append to temp file
process_file() {
local FILE="$1"
echo -e "# -------" >> "$TEMP_FILE"
echo "# $FILE" >> "$TEMP_FILE"
# Remove the frozen string comment and the line immediately after it if it's empty
awk '
BEGIN {skip = 0}
/^# frozen_string_literal: true$/ {skip = 1; next}
skip && NF == 0 {skip = 0; next}
{skip = 0}
{print}
' "$FILE" >> "$TEMP_FILE"
echo -e "\n" >> "$TEMP_FILE"
}
# Gather contents of each file with the filename as a comment
if [ -z "$EXTENSION" ]; then
find "$DIRECTORY" -type f | while read -r FILE; do
process_file "$FILE"
done
else
find "$DIRECTORY" -type f -name "*$EXTENSION" | while read -r FILE; do
process_file "$FILE"
done
fi
# Copy the gathered contents to the clipboard
pbcopy < "$TEMP_FILE"
# Clean up
rm "$TEMP_FILE"
echo "File contents copied to clipboard."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment