简体   繁体   中英

Delete all files from previous commits with git filter-branch

In my project in github I made big mistake , i forgot to add .gitignore in start , and more files were added to my repo. Now I've added .gitignore where are a lot of files and directories. I've done a lot of commits before this and Now I want to delete all unnecessary files from repo with command git filter-branch --tree-filter 'rm -f passwords.txt' HEAD . This command deletes password.txt from all previous commits , but I have two questions: 1) what if I want to delete all files that are in .gitignore? What I must to write after rm ?? 2) After input this command , git wrote me: " master branch and 'origin/master' have diverged. Use git pull.... ". I didn't use this command , I just use git push -u . Explain please what happened with my brancch? Why it is diverged? Ps I work alone with my project and have only one branch - master

  1. If your .gitignore lists only files (not directories or patterns) the command should be

    rm -f `cat .gitignore`

    I recommend to copy your .gitignore to a file out of Git tree to avoid Git changing the file while it filters commits. So:

     cp .gitignore ../gitignore git filter-branch --tree-filter 'rm -f `cat ../gitignore`' rm ../gitignore
  2. As for the second question — git filter-branch (like any other commit-editing command — amend, rebase, etc.) creates new commits, an entire new branch really, so you you cannot just push filtered branch. You have to force-push it, either with git push -f origin master or git push origin +master .

you should use git filter branch, imagine you want delete all target/ dirs in your previous commits, you can run just 4 commands for that works:

$ git filter-branch --tree-filter 'rm -f */target' HEAD

$ rm -rf */target (you use this one to delete target/ dirs on current HEAD)

$ git commit -am 'delete all target/ dirs' --allow-empty

$ git push

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM