Last active
August 16, 2023 11:49
-
-
Save kingcc/29f906ec89a5ba72e1517552f3d9e1d4 to your computer and use it in GitHub Desktop.
modify date & time of git commit to match its message
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 | |
# This script is designed to find the latest Git commit that contains a date, | |
# and then change its commit date to a specified date. To achieve this goal, | |
# the script performs the following operations: | |
# | |
# Use the git log command to find the SHA of the latest Git commit that contains | |
# a date. | |
# Extract the date string from the commit message of the identified commit. | |
# Convert the date string to a format that Git can accept using the date command | |
# with the -d or -j option, depending on the system type (macOS or other systems | |
# ). | |
# Modify the author and commit date of the identified commit using the git | |
# filter-branch command. | |
# Note that modifying the commit date of a Git record can cause confusion in | |
# the Git history, so please make sure to back up your repository before | |
# performing this operation and consult with other developers if necessary. | |
# | |
# e.g. | |
# When you execute this script, the submit date of a commit with message | |
# `feat(08/16): add script for change commit date ` will change to `08/16` | |
#!/bin/bash | |
# Find the SHA of the latest n commits that contain a date | |
n=${1:-1} | |
shas=$(git log --grep='([0-9]\{2\}/[0-9]\{2\})' --pretty=format:%H -$n) | |
# Loop over each commit to extract the date from the commit message | |
for sha in $shas; do | |
commit_date=$(git log --format=%B -n 1 $sha | grep -o '([0-9]\{2\}/[0-9]\{2\})' | tr -d '()') | |
if [[ -n $commit_date ]]; then | |
# Format the date string to a format that Git can accept | |
if [[ "$(uname)" == "Darwin" ]]; then | |
# On macOS, use the following format to convert the date string | |
year=$(date +%Y) | |
hour=$(date +%H) | |
minute=$(date +%M) | |
second=$(date +%S) | |
git_date=$(LC_TIME=en_US.UTF-8 date -j -f "%m/%d/%Y %H:%M:%S" "$commit_date/$year $hour:$minute:$second" +"%a %b %d %H:%M:%S %Y %z") | |
else | |
# On other systems, use the following format to convert the date string | |
git_date=$(date -d "$commit_date $(date +%Y)" +"%a %b %d %H:%M:%S %Y %z") | |
fi | |
# Modify the commit date | |
FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --env-filter \ | |
"if [ \$GIT_COMMIT = $sha ] | |
then | |
export GIT_AUTHOR_DATE='$git_date' | |
export GIT_COMMITTER_DATE='$git_date' | |
fi" | |
else | |
echo "No commit message containing date found in $sha." | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment