How to merge specific files from another branch/repository

Let says you are working on a project and you have dependencies of code from some another repository, which you need in your project code.

  • One way is to copy the code from another repository manually to yours whenever it gets update not so good way 😦
  • Another way is to use git version control system to do that for you and its super easy to do 🙂

Let me show you how we can do it.

Fetching from Another Repository

git add remote other <repository_link>
git fetch other
git checkout <your_target_branch>
git checkout -p other/target-branch file_path

If you have multiple files you have to just change the last checkout statement to

git checkout other/target-branch file_path1 file_path2

But wait there is one catch here that is the path of the file in your repository should be a mirror image (same as) of the path of the file in another repository you are fetching from.

Fetching from Same Repository

Now If you want to fetch files from another branch of the same repository you have to just do

git checkout other_branch_name file_path1 file_path2

I have to admit that it has been three years now working with git, but it still excites me that there is lot of things that I do not know about git, If you also have some important time-saving git commands which you feel can save someone else time do share in comment because sharing is caring :sunglasses: .

Cheers!

Happy Coding


Photo by Yancy Min on Unsplash