更改git历史,同时保留GPG签名的时间戳

46qrfjad  于 5个月前  发布在  Git
关注(0)|答案(1)|浏览(80)

我试图在将旧的本地仓库的git历史中删除敏感数据,然后将其推送到Github,同时保持/伪造原始的GPG签名时间戳。
我知道不建议这样更改git历史记录,但我真的需要删除这些敏感数据,同时维护GPG时间戳(即使我知道哈希值会有所不同)。
我以前可以通过以下方式做到这一点:
我会运行git rebase -i {HEAD}(HEAD是我想要编辑的提交之前的提交),然后选择编辑所需的提交,然后运行:

  1. sudo date -f "%s" {UNIX-TIMESTAMP}
  2. GIT_COMMITTER_DATE="$(date)" git commit -—amend --date="$(date)" -S
    第一个命令是将机器的日期更改

    这在过去很好用,但是现在当我尝试运行它时,所有在我想要编辑的提交之后的提交都会有一个新的GPG签名时间戳,这个时间戳与我选择用来编辑所需提交的UNIX-TIMESTAMP相同,当我将它推送到Github时,这将是可见的。
    我也试过GIT_COMMITTER_DATE="$(date)" git commit -—amend --no-edit --date="$(date)" -S,但它导致了同样的问题。
    在运行git rebase —continue之后,我该怎么做来维护后续(和未编辑的)提交的GPG时间戳?或者还有其他方法可以做到这一点吗?
mec1mxoz

mec1mxoz1#

(首先,备份您的存储库!)
我不认为Git会支持在这样的操作中保留GPG时间戳。
确定你想要编辑的提交的哈希值(Commit B)。然后开始一个交互式的变基,从你想要编辑的提交的父提交开始。

git rebase -i <commit-hash>^

字符串
在交互式变基todo列表中用edit标记你想要编辑的提交。然后用你的修改修改提交。

git commit --amend -S


继续进行变基(git rebase --continue)。
对于随后的每次提交,将GIT_COMMITTER_DATE重置为原始提交日期。这可以通过脚本自动完成。
您可以使用脚本来自动重置GIT_COMMITTER_DATE。此脚本将:

  • 提取每个提交的原始提交日期。
  • GIT_COMMITTER_DATE设置为此原始日期。
  • 修改每个提交而不改变其内容(git commit --amend --no-edit -S)。
#!/bin/bash

# The hash of the first commit to start processing (exclusive)
START_COMMIT="<commit-hash>"

# Checkout to a temporary branch to avoid directly modifying the main branch
git checkout -b temp-branch

# Iterate over each commit from HEAD to START_COMMIT
while [ $(git rev-parse HEAD) != $START_COMMIT ]; do
    # Get the original author date
    AUTHOR_DATE=$(git show -s --format=%aI HEAD)

    # Amend the commit without changing its message/content, but reset the author date
    GIT_COMMITTER_DATE="$AUTHOR_DATE" git commit --amend --no-edit -S --date="$AUTHOR_DATE"

    # Move to the previous commit
    git reset --soft HEAD~1
done

# Finally, rename the temporary branch back to the original branch name if needed
git checkout -b new-branch-name
git branch -D temp-branch

echo "All commits amended with original author dates."


也可以使用git filter-branch

#!/bin/bash

# The range of commits to process, e.g., master..feature-branch
COMMIT_RANGE="<commit-range>"

# Function to extract and set the original author date for each commit
export -f set_original_date
set_original_date() {
    # Extract the original author date
    local AUTHOR_DATE=$(git log -1 --format=%aI $GIT_COMMIT)

    # Set the GIT_COMMITTER_DATE to the original author date
    export GIT_COMMITTER_DATE=$AUTHOR_DATE
}

# Run git filter-branch with the above function
git filter-branch --env-filter 'set_original_date' $COMMIT_RANGE


在完成rebase并确保所有日期都正确之后,您可以将更改推送到GitHub。

相关问题