Mazzy
Mazzy

Reputation: 14179

Have two different copies of same file in two different branches

Do you know how could I have two different copies of the same file in two different branches in git?

Let assume I have a file called config.
What I'm trying to achieve is have a copy of this file in the dev branch different in the master branch.

The important thing is that file can't be ignored in the gitignored.

Upvotes: 3

Views: 1852

Answers (1)

CodeWizard
CodeWizard

Reputation: 141946

You can checkout the 2 branches. modify the file and commit them to each branch.

If you want to merge the branches and to have 2 separate files (different content) in each branch, commit the changed to the branches and then set the desired file tin your .gitattributed to always grab the ours file - which will result in this file to never be overwritten

Read all about it and to set it up here:
https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#Merge-Strategies

You can also use Git attributes to tell Git to use different merge strategies for specific files in your project.

One very useful option is to tell Git to not try to merge specific files when they have conflicts, but rather to use your side of the merge over someone else’s.

This is helpful if a branch in your project has diverged or is specialized, but you want to be able to merge changes back in from it, and you want to ignore certain files.

config_file merge=ours

As @torec mentioned in his comment:

Beware of what I consider a bug in git: if git is able to trivially merge the file it will not run your custom merge driver. Git always tries a simple 2-way merge first, before attempting the 3-way merge

So another option is to use smudge/clear filter to make sure you have the right file.

Smudge

Read all about it and to set it up here:
https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes

It turns out that you can write your own filters for doing substitutions in files on commit/checkout.

These are called clean and smudge filters.

In the .gitattributes file, you can set a filter for particular paths and then set up scripts that will process files just before they’re checked out (“smudge”, see Figure 8-2) and just before they’re staged (“clean”, see Figure 8-3).

These filters can be set to do all sorts of fun things.

enter image description here

Upvotes: 1

Related Questions