You are working on your python project with your team. One day after a`git pull` your web application doesn't start. On checking logs, you find an`import error`. After debugging for a bit, you find out that one of your teammates has installed a new dependency. The new library is used in the latest commit but not installed in your`virtualenv`. You version your`requirements.txt` file in`git`. You should have installed the new dependency after a the`git pull`. Do you remember to do`pip install` every time you do a`git pull`? Would you like to do it every time like a robot? I would not. So what do you do when you have to take care of a monotonous task? The answer is simple to automate it. But how? Again answer is simply write a simple bash script. But how would the script know when to run the`pip install`? Good question. The answer is`git` hooks.
Git Hooks
“Git hooks are scripts that Git executes before or after events such as: commit, push, and receive. Git hooks are a built-in feature — no need to download anything. Git hooks are run locally.”
read more about it here
Now we will use a`post-merge` hook provided by git. As the name suggests, post-merge hook can be used to run a task after every merge. We will write a simple shell script which will execute on every merge. The script will detect the change in your requirements.txt file, and in case of a change it will run`pip install` to fetch the latest dependencies.
Follow the steps to get it running.
- `cd` into your`.git` directory.
- Open the file`hooks/post-merge` using any editor.
- Copy and paste the following code and change the paths to your`virtualenv` and`requirements.txt` file. Save this file when you are done.
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"check_and_run() { echo "$changed_files" | grep --quiet "$1" && eval "$2"}check_and_run requirements.txt "/path/to/virtualenv/bin/pip install -r /path/to/requirements.txt"
- Make this file executable using`chmod +x hooks/post-merge`
That’s it. No longer you have to install the dependencies manually whenever there is a change in the dependencies of your project.
originally published on Medium (January 2017): https://medium.com/asymmetry/auto-install-dependencies-68fc721190a9

