Home > Blockchain >  Automatically change code based on git branch
Automatically change code based on git branch

Time:10-22

I have a code base with two branches: master and experimental.

For testing purposes I have to use a different database and apiKey. It's a hassle when I have to merge changes and it creates a conflict.

Is there anyway to manage this automatically based on the branch name?

In master it's:

mongoose.connect('mongodb://127.0.0.1:27017/'   'oysterDB');
apiKey = '123ZXC'

In experimental it's:

mongoose.connect('mongodb://127.0.0.1:27017/'   'testingDB');
apiKey = 'QWERTY123'

CodePudding user response:

One common way to achieve this is by reading the variables from a separate untracked file. For example:

  1. Create a new file called config.json.
  2. Update your application to read the variables from the new config.json file.
  3. Add the new file to your .gitignore file so that you do not track it in the repo.
  4. Create different versions of the file such as config.json.master and config.json.experiemental, and change the settings accordingly. If implemented properly you can commit these files along with the .gitignore change into the repo and that commit can be safely merged into all branches. (Consider omitting passwords or sensitive keys from the json files you are committing.)
  5. Create a post-checkout hook. Inside this hook you can look at the currently checked out branch (perhaps using the command: git branch --show-current), and based on what it is you can copy the appropriate json file to config.json so your app will use that set of variables.

Once the above steps are implemented, as soon as you switch branches your config.json will automatically be updated, and your git status will remain clean.

Tip: Anytime you (or others) might want to override the configs yourself, you could disable the hook temporarily and edit config.json manually. Or, perhaps you could add another file to your .gitignore file called config.json.local, and setup your hook to copy that file in place when you're not on one of the two shared branches. That way every developer can have their own private copy of the config file that is untracked, if desired. (Please note the local version would be missing from fresh clones.)

  • Related