Sunday, July 10, 2016

Split and move a file using git while preserving history

Everyone is using Git these days. A very well known use of Git is taking place at GitHub.

On a day to day basis, people tend to push commits to different branches and with these commits, history is being built up. This history can be used to understand certain bits of code that have been modified by you or someone else in a certain user story. It can help very much when trying to get some context about that portion of the code.
It can also be used to blame someone when they've did mistakes, but that's just bad ]:)

Given the above, some projects require, all should require, to preserve history on every action that can be performed on Git.

Some of the actions are:

  1. Move
  2. Move & edit
  3. Split a file into multiple files(usually two)


Moving a file from a location to another is easy as copy-pasting. Git is able to track these changes without any human intervention.

Move & edit

This is very similar with moving a file, the only difference is that you can also rename the file and also edit its contents. This action can also be tracked by Git automatically.

Split a file into multiple files(usually two)

Although this might seem like a Move & edit, it is much more interesting.
Splitting a file means that its contents should be present in both places, if splitted in two files, at the same time. This action cannot be tracked by Git automatically and it needs a little more human intervention. Quite a little more.

The idea behind this solution is to create a new branch and then move the same file in both branches. Do be careful to move them in different places or different names. After this, merge the new branch into 'master', which is the branch from which you've created the new branch.

You will have to use the following merge command while having the 'master' branch active:

git merge --no-ff 'new_branch'

The merge process will give you three conflicts. You'll have to keep both files from each branch and delete the file that was moved from both branches.

This action will preserve the history on both files.

Full process description can be found on GitHub

Next steps:

  • Split and move a file using TFS while preserving history

Related posts:

No comments:

Post a Comment

Keep it technical and related to the subject matter. Personal comments of any kind will be deleted.