Git: copy all files in a directory from another branch
GitFileCopyBranchGit Problem Overview
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?
Git Solutions
Solution 1 - Git
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
Solution 2 - Git
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')
Solution 3 - Git
To copy the directory without tracking it:
git restore --source master dirname
Solution 4 - Git
In my case this simplest solution to get files from the origin branch directory was:
- origin - remote repository alias(origin by default) sourceBranchName
- branch with required files in directory
- sourceBranchDirPath - relative/absolute path to the required directory with
files
git checkout origin/sourceBranchName -- sourceBranchDirPath
Example:
git checkout origin/validation_fix -- src/test/java/validation/
> Result was all files from origin/validation_fix branch by > src/test/java/validation/ relative path in the draft > mode(uncommited)