Dealing with config files in Git

So while developing for my job, I’ve come across an interesting challenge. How does one automatically change config file values based on the branch they are currently using in Git?

Background

So for one of my projects, we have a website that is used on several domains. Due to certain constraints and history of our project, we have forked the website into two versions. Each version has its own master branch (Master and Master_ExtraFeatures).

Master_ExtraFeatures always contains all the features of master, but also contains some additional code.

When testing Master_ExtraFeatures, we have to modify the config file a little bit. Since we do not keep the config files as part of the Git repository, the config does not change when I checkout Master or Master_ExtraFeatures. I have to manually update the settings, or I have to copy in a file from elsewhere.

Solution

This is by no means the only way to do it, but it works good for me. Basically, I wanted to write a script that would hook into the git process and modify the config file every time I checkout a new branch.  Clearly, this is a good candidate for Git hooks. I created a file in my .git folder called “post-checkout”.  This will be executed every time a branch is checked out. Then I added the following code:

branch=$(git rev-parse –abbrev-ref HEAD)

if [[ $branch == *ExtraFeatures* ]]
then
sed -i ‘/EXTRA_FEATURES_ENABLED/s/FALSE/TRUE/g’ /home/me/projects/website/config.php
else
sed -i ‘/EXTRA_FEATURES_ENABLED/s/TRUE/FALSE/g’ /home/me/projects /website/config.php
fi

Explanation

branch=$(git rev-parse –abbrev-ref HEAD)

  • Gets the newly checked out branch name.

if [[ $branch == *ExtraFeatures* ]]

  • Checks if the branch name contains “ExtraFeatures”. The asterisks are to wildcard the phrase.

sed -i ‘/EXTRA_FEATURES_ENABLED/s/FALSE/TRUE/g’ /home/me/projects/website/config.php

  • This is the ‘sed’ command. It is basically used for string and file manipulation. For your purposes, the format should be similar to this:
    • sed -i ‘/[PHRASE TO LOOK FOR ON A LINE IN THE FILE]/s/[PHRASE THAT WILL BE CHANGED ON THAT LINE]/[CHANGE THE PHRASE TO THIS]/g’  [COMPLETE FILE LOCATION FOR FILE THAT WILL BE SEARCHED]
    • The -i flag in sed says that the file will be written. If you want to try it without overwriting your file, skip the -i, the changes will instead be written to standard out.

You will notice I have two lines with sed. Basically this example is a simple toggle that will change the EXTRA_FEATURES_ENABLED setting from true to false.  So my config.php file changes:

from this:

define(‘EXTRA_FEATURES_ENABLED’,FALSE);

to this:

define(‘EXTRA_FEATURES_ENABLED’,TRUE);

No additional lines are affected, which is exactly what I wanted.

Leave a Reply