Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move function declaration to another file yet retain Git history?

I am refactoring a single-file PHP script to declare functions and classes in separate files. How does one move a block of code from one file to another file yet preserve the Git history for each individual line? I would like the ability to use at the very least git blame on the code. Comparing to older versions would also be helpful.

Note that I am not interested in 'workaround' solutions that would require additional commands or flags (such as --follow) on the code to view its 'old' history, for which the person viewing the history would have to know that the file needs special treatment. I am looking for a solution which writes the necessary metadata such that normal git commands such as blame, log, diff, and such 'just work' without presenting to them additional flags or arguments.

I have read quite a few posts looking for solutions to similar problems, but none that address the issue of git blame on individual lines. One solution that I think would work would be to copy the file and its entire history, then work off of that. However, that question remains without a satisfactory answer.

like image 953
dotancohen Avatar asked Jul 17 '13 11:07

dotancohen


1 Answers

Warning: This assumes that rewriting history is acceptable. Do not use this unless you know the implications of rewriting history.

To split a file into multiple files while maintaining history use git filter-branch:

git filter-branch --tree-filter 'if [ -f original.php ]; then 
    echo part1.php part2.php part3.php | xargs -n 1 cp original.php; fi' HEAD

Then delete the lines that you do not want from each file (leaving only the desired functions and classes) and commit the result!

like image 123
onionjake Avatar answered Oct 21 '22 14:10

onionjake