Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can sync some files between two branches in git?

Tags:

git

I have problem with git and my repo.

First I write example

git checkout Proj1
# modify index.html
git commit -am "Modify Index.html"
git checkout Proj2
git show Proj1:index.html > index.html
git commit -am "Modify Index.html"
git checkout Proj1

This is my way to keep the same file content in two branches.

Of course I can use cherry-pick if the commit only contain the file I want to sync. How can we sync files between two branches in git?

Do you have any short solution for this problem.
Maybe some alias to write?
Where I can keep file with list of files to sync?

like image 479
machmet Avatar asked Apr 05 '16 07:04

machmet


People also ask

How do I connect two branches?

To merge branches locally, use git checkout to switch to the branch you want to merge into. This branch is typically the main branch. Next, use git merge and specify the name of the other branch to bring into this branch. This example merges the jeff/feature1 branch into the main branch.


1 Answers

If you dont care about history, then you can make a separate commit on branch 2 containing the file exactly as it looks like on the tip of the commit in Proj1:

git checkout Proj2
git checkout Proj1  -- index.html

git commit -am "Modify Index.html"

Essentially, this means to take the file EXACTLY as it looks in Proj1 branch.

git checkout -- means that after the dash you provide a filename (or path). This can be useful, also if you want to change some files in your repository and preserve others.

Then, if you want, you can also reuse the commit message from the commit you made in Proj1 like this:

git checkout Proj2
git checkout Proj1  -- index.html

git commit -a -C Proj1

Git commit -C means to reuse the commit comment you already had.

From the git documentation "git checkout":

git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>

When or --patch are given, git checkout does not switch branches. It updates the named paths in the working tree from the index file or from a named (most often a commit).

[...]

git checkout with or --patch is used to restore modified or deleted paths to their original contents from the index or replace paths with the contents from a named (most often a commit-ish).

And from the git documentation "git commit"

git commit -C <commit>

--reuse-message=<commit>

Take an existing commit object, and reuse the log message and the authorship information (including the timestamp) when creating the commit.

like image 91
Jesper Rønn-Jensen Avatar answered Oct 18 '22 16:10

Jesper Rønn-Jensen