Context
Imagine you are working with a git workflow where you want to map each branch that should eventually be merged into the main branch, but you map each branch to a given Jira Issue or others, but you have a process for merging that is convoluted and slow.
You want to keep your work repeating yourself and reuse the work you have done but its still stuck in a to-be approved branch, just to tweak for instance some variables or others to switch environments, regions etc in a Infrastructure as Code world this is very common.
How to copy a folder from a different git branch on the same repo
Using git restore
1
git restore
This is how you can do it
1
git restore --source my-stale-branch the-folder-i-need/
The you can use mv as git restore doesn’t have an option to specify the folder to where you would paste it.
You could then create a small script to just paste it to the correct folder
1
git restore --source my-stale-branch the-folder-i-need/some-nested-folder/ && mkdir -p the-folder-i-need/
This option doesn’t automatically stages the changes. It just copies the content over, so its a better option than using alternative option such as git checkout, which automatically stages changes.
If you need to have changes staged, you can also make use of
1
-S, --staged restore the index
And in case you need the worktree
1
-W, --worktree restore the working tree (default)
Conclusion
This is a simple solution to restoring a folder from a given branch to your current working branch to allow parallelizing similar work when you have a git workflow that stays longer in the merge into main branch phase due to either long CI pipelines, waiting on peer feedback with several approver etc..