How to "delete" history in Git feature branch

180 views Asked by At

In a feature branch (cloned from master) we added some files and than deleted them. The same files where added to the master branch.

When we now try to merge back the feature to the master the files in the master get deleted (my understanding is, because the information "we don't need these files" is stored in the feature branch)

Which git command can we use to ignore or delete this "historic knowledge" in the feature branch?

2

There are 2 answers

0
Joshua Zeltser On

Once you merge your feature branch into the master branch, git checks for any changes in your feature branch to apply to master. Therefore, if a file is deleted from your feature branch, after merge to master, the file will also be deleted from master. So you either need to add the file back to the feature branch and merge to master or just readd the file to master.

2
LeGEC On

You can :

  • live with the merge commit that "deleted" those files, and create a new commit on top which re-adds them :
# <sha> should refer to a commit where the files exist, and have the content you want
git restore --source=<sha> -SW -- path/to/file1.txt path/to/file2.txt

# create a commit, with a meaningful comment
git commit -m "restore files"
  • modify the merge commit itself, and push that (or force push if the merge commit was already shared) :
# assuming you are on the merge commit itself:
git restore --source=<sha> -SW -- path/to/file1.txt path/to/file2.txt

# use --amend to edit it:
git commit --amend

# force push the result:
git push --force-with-lease

If you are on the merge commit, and the files were on the current branch right before merging, you can use HEAD~ to point at "the commit right before":

git restore --source=HEAD~ -SW -- path/to/file1.txt path/to/file2.txt

before the facts:

it is a good idea to have a clear view of your commits and branches before doing a merge (even if you go through a Pull Request)

You can use git log with a few options to have a nice view in your terminal:

$ git log --oneline --graph master feature

you may read git help log to see all the options you can have, or google for "how can I view [this and that] with git log ?"

or use a graphical frontend with a clear view of your repo history.