home about me

Change project config when git branch changes

For a legacy project that required me to deploy different branches to different endpoints, I utilized a quick git hook.

This legacy project is a Shopify template using the (deprecated) theme cli. The way this works is that it reads a config.yml in the root project directory, and uses the information stored in there for deployments (theme deploy).
There are two deployment branches in this project, which each correspond to a separate Shopify shop - b2b and b2c. They’re mainly the same, but one might get a few minor changes the other doesn’t.

For newer projects, you could just link the git branch directly to the shop’s theme, but the technique outlined here might be valuable in other situations too - anytime you need to change something based on the branch you’re on, really!

I’ve created two config files - in this example config-b2b.yml and config-b2c.yml - populated them with their corresponding deployment information, and added them to the gitignore file.
Then I’ve created a file called post-checkout inside the .git/hooks folder of the project, made it executable (chmod +x .git/hooks/post-checkout) and populated it with a tiny shell script:

rm config.yml 2>/dev/null
cp "config-"`git branch --show-current`".yml" config.yml 2>/dev/null

First, the current config.yml gets deleted. Then the config file named after the new branch name is copied in its place. The two 2>/dev/null commands just prevent error messages from showing up, in case we navigate to a branch or commit without corresponding config file.

This runs automatically behind the scenes and makes sure I’m always on the right branch when it comes to manual deployments (yuck 🫥).