add: added resign_commits.sh

This commit is contained in:
Denis Evers 2023-06-24 10:44:02 +08:00
parent ee8bc0bbba
commit 13f2d61e19
Signed by: denis-ev
GPG Key ID: 10BFC1EB323A6CA8
1 changed files with 76 additions and 0 deletions

76
resign_commits.sh Executable file
View File

@ -0,0 +1,76 @@
#!/bin/bash
set -x
REPO_PATH="$1" # Get repository path from command line argument
OLD_BRANCH="$2" # Old branch to resign commits
NEW_BRANCH="new_${OLD_BRANCH}" # New branch name
# Check if the repository path and branch are provided
if [ -z "$REPO_PATH" ] || [ -z "$OLD_BRANCH" ]; then
echo "Please provide the path to the Git repository and the branch name."
echo "Usage: ./resign_commits.sh /path/to/repository branch_name"
exit 1
fi
# Check if the repository path is valid
if [ ! -d "$REPO_PATH/.git" ]; then
echo "Invalid repository path: $REPO_PATH"
exit 1
fi
cd "$REPO_PATH" # Move to the repository directory
commits=() # Array to store commits
# Check out the old branch
git checkout "$OLD_BRANCH"
# Iterate through all commits in the repository in reverse order
for commit in $(git rev-list --reverse HEAD); do
commits+=("$commit")
done
if [ ${#commits[@]} -eq 0 ]; then
echo "No commits found."
exit 0
fi
# Delete the new branch if it already exists
if git show-ref --verify --quiet refs/heads/"$NEW_BRANCH"; then
git branch -D "$NEW_BRANCH"
fi
# Create a new branch from the first commit in the repository
git checkout --orphan "$NEW_BRANCH"
# Reset to have a clean working directory
git reset --hard
# Resign and cherry-pick each commit
for commit in "${commits[@]}"; do
echo "Resigning and cherry-picking commit: $commit"
if ! git cherry-pick "$commit"; then
# If cherry-pick fails (e.g., due to a conflict), abort the operation
git cherry-pick --abort
echo "Failed to cherry-pick commit: $commit. Aborting."
# Switch back to the old branch and delete the new branch
git checkout "$OLD_BRANCH"
git branch -D "$NEW_BRANCH"
exit 1
fi
git commit --amend --no-edit --gpg-sign --reset-author
done
# Switch to the new branch
git checkout "$NEW_BRANCH"
# Delete the old branch locally
git branch -D "$OLD_BRANCH"
# Rename the new branch to old branch name
git branch -m "$NEW_BRANCH" "$OLD_BRANCH"
# Force-push the branch to the remote
git push origin "$OLD_BRANCH" --force
echo "All commits successfully resigned, old branch replaced and force-pushed."