Reputation: 1029
I am working on a branch B. I created my branch and checked out from the latest master commit. My colleague worked on a branch A. He checkout a long time ago from master so he's behind it:
--------- A1
/
/
/
--------- M1 --------- M2 --------- M3 --------- M4 --------- M5 --------- B1
In his branch he worked on a lot of files and I only need some of them. Let's call them File1.txt, File2.txt and File3.txt. I would like to merge these files to my branch. My question is: What's the approach to follow in this case? Should I merge/rebase on top of his outdated branch ? Is there a way to just get these 3 files and merge them to my current working branch and get a B2 commit?
Upvotes: 5
Views: 1508
Reputation: 86
You can use git checkout --patch <branch> <filename>
to patch already existing files in your current branch by using files from another branch. If the file does not exist in your current branch, use git checkout <branch> <filename>
to edit it in your branch. Next, you can save the files and commit changes.
In your case (example for file1.txt):
Go to branch B with
git checkout B
Use git checkout --patch A file1.txt
or, if the file1.txt does not exist in branch B, use git checkout A file1.txt
On Apply this hunk to index and worktree
choose y
Save the file and git add file1.txt
and commit your changes with git commit -m 'Your commit message'
Here is a specific description of the git checkout --patch
taken from git-scm.com:
-p
--patch
Interactively select hunks in the difference between the <tree-ish> (or the index, if unspecified) and the working tree. The chosen hunks are then applied in reverse to the working tree (and if a <tree-ish> was specified, the index).
This means that you can use git checkout -p to selectively discard edits from your current working tree. See the “Interactive Mode” section of git-add[1] to learn how to operate the --patch mode.
Note that this option uses the no overlay mode by default (see also --overlay), and currently doesn’t support overlay mode.
Hope this helps.
Upvotes: 6
Reputation: 52236
If you need : the files File{1,2,3}.txt
as they are in A1
, discarding all changes introduced on these files during M2..M4
, just use :
git checkout A1 -- File1.txt File2.txt File3.txt
If you really need to merge (combine the changes in A1
with the changes in M2..M4
), you can create a commit with only these files, and use that commit :
# create a branch from A1 :
git branch wip A1
git checkout wip
# replay changes only for the files
git reset HEAD^
git add File1.txt File2.txt File3.txt
git commit
git checkout . # drop other changes
# use merge or rebase to combine the changes
git rebase M4
Upvotes: 0