Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to merge specific files in git

Suppose I have a project on MASTER branch with 100s of php files. To do a bug fixing in the project, i create a separate branch

git checkout -b bugfix

Then after fixing the bug in 3 files (for eg index.php, register.php and login.php), i merge it in the master branch

git checkout master
git merge bugfix

The above code will merge all the 3 files i made changes, but is there anyway that i can force GIT to merge only 2 files, say login.php and register.php only?

like image 964
Phantom007 Avatar asked Jun 07 '13 08:06

Phantom007


People also ask

Can I merge specific commit?

The git merge command is targeted at combining two branches. You can also use it for merging several commits into a single history. The merge commits involve two parent commits. Every time a new merge commit is made, git runs an automate merging of different histories.

Can you cherry pick a merge?

Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.


1 Answers

There are two approaches:


Approach 01

The following solution is adopted from a blog post

It turned out that checkout can also be helpful in this matter. You can simply callout (checkout) those specific files from another branch:

# switch to the branch you want to be your merge destination
git checkout master

# checkout specific files from specific branch (e.g bugfix)
# format: git checkout <source branch> <file.1> <file.2> ... <file.N>
git checkout bugfix login.php register.php

# check the status
git status

# merge them in
git commit -m "your merge comment"

Approach 02

This is an easy alternative approach, but it only works if you have one commit per file (meaning every time you have changed a file, you have made one commit and then have moved to the next file). In this case you can simply bring those specific commits to the other branch (in your case the master branch):

# get which commit you want to take to the other branch (first 7 characters will do)
git log

# switch to the branch you want to be your merge destination
git checkout master

# bring specific commit to this branch (replace the 63344f2 with your own 7 character commit ID)
git cherry-pick 63344f2
like image 127
Mehrad Mahmoudian Avatar answered Oct 12 '22 16:10

Mehrad Mahmoudian