Skip to content

Instantly share code, notes, and snippets.

@iamsonal
Created March 27, 2025 01:33
Show Gist options
  • Save iamsonal/93c455c446934f413aab474fee17046e to your computer and use it in GitHub Desktop.
Save iamsonal/93c455c446934f413aab474fee17046e to your computer and use it in GitHub Desktop.
#!/bin/bash
# Exit immediately if a command fails
set -e
# Store the current branch name
ORIGINAL_BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Check if PR number is provided
if [ -z "$1" ]; then
echo "❌ Error: Please provide a PR number."
echo "Usage: ./backup_pr_files.sh <PR_NUMBER>"
exit 1
fi
PR_NUMBER=$1
BACKUP_DIR="backup_pr_${PR_NUMBER}"
ZIP_FILE="${BACKUP_DIR}.zip"
BACKUP_LOCATION="./backups"
echo "πŸ” Current branch: $ORIGINAL_BRANCH"
# Fetch the PR branch from GitHub
echo "πŸ“₯ Fetching PR #${PR_NUMBER}..."
git fetch origin pull/${PR_NUMBER}/head:pr-${PR_NUMBER}
# Checkout to the PR branch
echo "πŸ”„ Switching to PR branch..."
git checkout pr-${PR_NUMBER}
# Get the list of changed files
echo "πŸ“„ Identifying changed files..."
git diff --name-only develop...pr-${PR_NUMBER} > changed_files.txt
# Create backup directory
echo "πŸ“‚ Creating backup directory: ${BACKUP_DIR}..."
mkdir -p ${BACKUP_DIR}
# Copy changed files to the backup directory
echo "πŸ“‘ Copying changed files..."
while read -r file; do
if [ -f "$file" ]; then
mkdir -p "${BACKUP_DIR}/$(dirname "$file")"
cp --parents "$file" "${BACKUP_DIR}/"
fi
done < changed_files.txt
# Create ZIP archive
echo "πŸ“¦ Creating ZIP archive: ${ZIP_FILE}..."
mkdir -p ${BACKUP_LOCATION}
zip -r ${BACKUP_LOCATION}/${ZIP_FILE} ${BACKUP_DIR}
# Cleanup: Remove temporary files and backup directory
echo "🧹 Cleaning up temporary files..."
rm -rf ${BACKUP_DIR}
rm changed_files.txt
# Return to the original branch
echo "πŸ”„ Switching back to the original branch: ${ORIGINAL_BRANCH}..."
git checkout ${ORIGINAL_BRANCH}
echo "βœ… Backup completed successfully!"
echo "πŸ“ The ZIP file is located at: ${BACKUP_LOCATION}/${ZIP_FILE}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment