Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

How do I merge a sub directory in Git?

Is it possible to merge only the changes for a sub-directory from a local Git branch to a remote Git branch or is it "all or nothing"?

For example, I have:

branch-a
 - content-1
 - dir-1
   - content-2

and

branch-b
 - content-1
 - dir-1
   - `content-2

I only want to merge the contents of branch-a dir-1 with the contents of branch-b dir-1.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just as an alternative to the SO question "How do you merge selective files with git-merge?", I just found this GitHub thread which could be more adapted for merging a whole subdirectory, based on git read-tree:

  • My repository => cookbooks
    My repository target directory => cookbooks/cassandra
  • Remote repository => infochimps
    Remote repository source I want merged into cookbooks/cassandra => infochimps/cookbooks/cassandra

Here are the commands I used to merge them

  • Add the repository and fetch it
git remote add -f infochimps git://github.com/infochimps/cluster_chef.git
  • Perform the merge
git merge --allow-unrelated-histories -s ours --no-commit infochimps/master

(this performs a merge by using the 'ours' strategy (-s ours), which discards changes from the source branch. This records the fact that infochimps/master has been merged, without actually modifying any file in the target branch)

  • Merge only infochimps/cookbooks/cassandra into cassandra
git read-tree --prefix=cassandra/ -u infochimps/master:cookbooks/cassandra

This reads the tree for only the required source subdirectory i.e. cookbooks/cassandra, on the upstream branch of the source repository.

Note that the target subdirectory name should also be cookbooks/cassandra, or you would see:

fatal: Not a valid object name
  • Commit the change
 git commit -m 'merging in infochimps cassandra'

Addendum

It's bizarre,[edit me] — but the read-tree step can possibly fail like this:

error: Entry 'infochimps/cookbooks/cassandra/README' overlaps with 'cookbooks/cassandra/README'. Cannot bind.

... even when both files are identical. This might help:

git rm -r cassandra
git read-tree --prefix=cassandra/ -u infochimps/master:cookbooks/cassandra

But off course, verify manually that this does what you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...