How to replace a string in a whole Git history?

后端 未结 3 1903
萌比男神i
萌比男神i 2021-01-05 04:05

I have one of my passwords commited in probably few files in my Git repo. Is there some way to replace this password with some other string in whole history automatically so

3条回答
  •  时光取名叫无心
    2021-01-05 04:55

    First, find all the files that could contain the password. Suppose the password is abc123 and the branch is master. You may need to exclude those files which have abc123 only as a normal string.

    git log -S "abc123" master --name-only --pretty=format: | sort -u
    

    Then replace "abc123" with "******". Suppose one of the files is foo/bar.txt.

    git filter-branch --tree-filter "if [ -f foo/bar.txt ];then sed -i s/abc123/******/g foo/bar.txt;fi"
    

    Finally, force push master to the remote repository if it exists.

    git push origin -f master:master
    

    I made a simple test and it worked but I'm not sure if it's okay with your case. You need to deal with all the files from all branches. As to the tags, you may have to delete all the old ones, and create new ones.

提交回复
热议问题