How can I sync other branch with mine while keeping specific directories?

Viewed 78

Here is what I did:

  • I have a "my_branch" and there is a "master" branch.
  • I kept committing my work to "my_branch" for, say one month.
  • To align with code in "master", for every 2 or 3 days, I merge master into "my_branch".
  • I change code under "my_dir/" only, while nobody else touched this directory
  • Other people change code under "somebody1/", "somebody2/" etc., but I had never touched.

Here is my problem:

  • For some reason which I don't know, files under directories other than "my_dir/" (which I didn't touch them) are not as same as what in "master".
  • One possible cause might be, when merging "master" into "my_branch", some files under directories other than "my_dir/" changed, and there were conflicts. Maybe I chose "resolve conflict" rather than "use theirs", and made me touched those files unintentionally.
  • Even if I keep merge "master" into "my_branch", those unintentionally changed files never get synchronized unless they are changed by somebody else in master.
  • If I merge "my_branch" into "master", files under directories other than "my_dir/" and inconsist with "master" will be changed because of "my_branch", and that's not what I want.

Here is what I want to do:

How can I make files other than "my_dir/" in "my_branch" to be same with "master", while keep files under "my_dir/" to be same with "my_branch"? One possible way is that I checkout "master", copy all files under directories like "somebody1/", "somebody2/" etc., to some place else, then checkout "my_branch", then copy those files back to my working directory and then commit.

But How can I do it with Git command? Does Git provide such util?

1 Answers

From your branch, assuming your remote is named origin

git fetch
git restore --source=origin/master .
git restore --source=my_branch my_dir/
git commit -am "Resynced everything but my_dir with master"

Edit after comments : in case you're running a version of git prior to 2.20.1 (thanks Vespene Gas for the reminder), you won't be able to use git restore. The alternative is the older command git checkout <ref> [-- <path> [<other_path>]]. Then again, as Matt rightfully pointed out, you might need to get rid of unwanted files in your repo after the operation with something like git clean)

Related