能否编辑Github提交历史记录?

3
在构建一个项目时,我使用了私有repo,并且为了更快的测试,我将数据库和其他凭证作为代码中的变量使用。现在项目依赖于环境变量,因此没有任何机密内容出现在repo中。我想要将其公开。但我不希望人们看到提交历史中包含这些凭证的部分。是否可能删除这些行或使所有提交历史变为私有?

为什么你的 GitHub 仓库包含敏感数据。它应该只存在于你的生产环境中,而不是 GitHub 仓库中。 - Arpit Solanki
你可以使用 git rebase -i 来改变历史记录。但是你需要创建一个全新的历史记录。 - choroba
明白了。谢谢。 - hitchnsmile
3个回答

8
您需要将上传到Github的任何凭证视为不再保密。即使您像其他人建议的那样rebase,删除它们,然后强制推送,一旦您将存储库公开,提交仍将通过URL(其格式基于提交ID)访问。

有两种方法可以使代码公开而不给他人访问您的凭据。

  1. 更改您的凭据,使存储库公开,并让其他人从您的错误中学习(我自己以前也上传过秘密文件,也看到其他有经验的开发人员这样做,所以不要感到孤单!)。

  2. 将存储库保持私有,创建一个本地副本,进行rebase(确保删除所有密码!),然后推送到新的公共repo。

我会选择选项1,但两个选项都是安全的。


2
这与GitHub自己提出的建议相一致 - “一旦您将提交推送到GitHub,您应该考虑其中包含的任何数据都已被泄露”。我也同意不要感到孤单 - 我们至少会做一次这样的事情:p - Joe Clay

2

两个答案都已过时。现在可以更改历史记录。

以以下内容为例,您拥有以下内容:

0c39034 commit you want removed
f7fde4a commit that you want to be in

请勿使用 revert,因为这样会导致以下问题:

e499d89 commit that supposedly reverts 0c39034

接下来,您需要执行以下操作来重新定位和压缩要删除的提交:

git rebase -i HEAD~3


pick f7fde4a commit that you want to be in
squash 0c39034 commit you want removed
squash e499d89 commit that supposedly reverts 0c39034
# Rebase 9fdb3bd..f7fde4a onto 9fdb3bd
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

执行 git log 命令以确认。

git log

推送您的更改:

git push --force

这样做将完全从您的历史记录中删除0c39034和e499d89。如果您拥有完整的提交ID,它们仍然可以在Web UI中访问。它会显示类似于:

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

我想以这句话作为结尾,@instantepiphany所说的最佳实践是正确的,确保不要在github上硬编码凭据。

0

6
对于阅读此答案的人,请注意上述方法仅更改提交消息,而不是代码。即使您使用“--amend”选项来修改代码,它也会创建一个新的提交,旧的提交仍然可以通过URL在github上访问。 - instantepiphany

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接