How to make Git preserve specific files while merging

  • e-mail server configuration that would use a local handling outside of production (e.g. through the excellent mailcatcher)
  • log configuration that would dump to local-disk files in dev, but consolidate to some central service otherwise
  • etc.

Git attributes

Check out our amazing Git-related video courses! Some of them are even free!

Merge drivers

Setting up

git config --global merge.ours.driver true
mkdir tmp
cd tmp
git init
git commit --allow-empty -m "chore: Initial commit"
echo 'email.json merge=ours' >> .gitattributes
git add .gitattributes
git commit -m 'chore: Preserve email.json during merges'

Prepping for a test run

echo 'Oh yeah' > demo-shared
git add demo-shared
git commit -m 'chore(demo): a file that will merge normally'
git checkout -b demo-prod
echo '{"server":"smtp.mandrillapp.com","port":587}' > email.json
git add email.json
git commit -m 'chore(email): production email.json'
echo -e "You know what?\nOh yeah" > demo-shared
git commit -am 'fix(demo): Header for the normal-merge file'
git checkout -
echo '{"server":"localhost","port":1025}' > email.json
git add email.json
git commit -m 'chore(email): dev/staging email.json'

echo -e 'You betcha' >> demo-shared
git commit -am 'fix(demo): Footer for the normal-merge file'

Alright, go!

(master) $ git checkout demo-prod
(demo-prod) $ git merge -
Auto-merging demo-shared
Merge made by the 'recursive' strategy.
demo-shared | 1 +
1 file changed, 1 insertion(+)

(demo-prod) $ cat email.json
{"server":"smtp.mandrillapp.com","port":587}

Want to learn more?

--

--

--

I make cool stuff and teach others to (Git, Rails, JS/CoffeeScript/Node/etc).

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Christophe Porteneuve

Christophe Porteneuve

I make cool stuff and teach others to (Git, Rails, JS/CoffeeScript/Node/etc).

More from Medium

Setup SSH and 2SV for Bitbucket in eclipse

Global Usings in C#10

Coding Guide Spotlight: Rego Style Guide