How do I copy all files in a directory from another branch? I can list all of the files in that directory by doing
git ls-tree master:dirname
I can then copy all of the files individually by doing
git checkout master -- dirname/filename
However, using wildcards has so far been a total fail. This does nothing:
git checkout master -- dirname/*.png
Though I guess I can use a bash script to do that, there has to be an easier way, right?
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use
git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')
If you want to preserve history, you could possibly try this... create a new target-branch
off of the master
before you experiment.
The steps below assume you have two branches target-branch
and source-branch
, and the directory dir-to-merge
that you want to merge is in the source-branch
. Also assume you have other directories like dir-to-retain
in the target that you don't want to change and retain history. Also, assumes there are merge conflicts in the dir-to-merge
.
git checkout target-branch
git merge --no-ff --no-commit -X theirs source-branch
# the option "-X theirs", will pick theirs when there is a conflict.
# the options "--no--ff --no-commit" prevent a commit after a merge, and give you an opportunity to fix other directories you want to retain, before you commit this merge.
# the above, would have messed up the other directories that you want to retain.
# so you need to reset them for every directory that you want to retain.
git reset HEAD dir-to-retain
# verify everything and commit.
While you are doing this, if you ever have to undo everything you did during the merge and restart from the point where created this new branch target-branch, you can do this (warning: will lose all changes made during the merge):
git reset
git checkout .
git clean -fdx