How I used cron to automatically simulate git activity
Tags: python, git, beginners, codenewbie
Published: 2022-02-23 14:31:10

A Crontab (CRON TABle) is a schedule of “cron entries” or in other words executable CLI commands to be run at specified intervals. You must be asking yourself: Why do I need these exactly?

In this tutorial I will take you through the basic usage of crontab, which is simply a list of commands that will automatically run from the time of a computer boot until it is told to stop. We will set crontab to execute three simple git commands:

1.  git add
2.  git commit
3.  git push

Before we dive into to the code, I want to discuss two possible implementations for automating git commands via use of crontab

### The Two Approaches

**Git Commands in Crontab Approach**

Inserting git commands directly into a crontab:
To explain this concept open a new terminal window and in the command line interface, type `crontab -e`
You should see a window like this pop up:

![cndkjcnd](https://miro.medium.com/max/700/1*3WGXf_8yofm8mhMq6TPULg.png)

Ok Great! Make sure to `press i`; and now you can freely add commands.
Any command that would typically execute through the command line will run here too. You need to specify how often you’d like the command to execute. To discuss this syntax in detail let’s examine the below chart:

![cdcdcd](https://miro.medium.com/max/700/1*tECL2YHlX0_DP7Ae1YlndA.png)

According to the illustration above- we could simply insert the chain of commands seen below in grey to indicate that:
At the forth minute, of the second hour, of every day, of every month,
we would like to git add, commit, and push a particular repository.
For more cron syntax click [here](https://crontab.guru/)!
It would look something like this:

```bash
4 2 * * * cd path/to/your/repository && git add . && git commit -m”another commit” && git push origin master
```

But this approach is too boring to even discuss… Instead, let’s write a python script that will execute these git commands for us. It will be a great way to introduce you to an awesome python module called GitPython and teach you how to run scripts that use dependancies via the crontab.

For this tutorial’s purposes I will assume that you already know how to set up a new virtual environment and that you’re fully capable of installing additional dependencies into this virtual environment.

ok… let’s get started with the script approach.

### The Script Approach: in 15 very short steps

 1. Set up a directory in your dev folder called cronGit (or really any name you want… just keep track because we will use paths later in this tutorial)
 2. Set up a new virtual environment, place it in this new directory, and make sure to add GitPython module as a dependency into this environment.
 3. For this tutorial we will use GitPython 2.1.11 you may add it using
    `(venv) $ pip install Gitpython == 2.1.11`
 4. Create a .gitignore file and don’t forget to add venv (or any other name used for the virtual environment)
 5. Create a new file called index.py in this root directory
 6. Create a new directory inside cronGit called `autoGitActivity`, or whatever you’d like.
 7. Inside this `autoGitActivity` folder let’s create a new empty text file and call it `activityTracker.txt`
 8. Now we must initialize a git repo inside this autoGitActivity folder we created, since this is where we will set a routine execution of git add, commit, and push commands… As a reminder you want to `git init`, and then `git remote add origin <link>`

![cdckdmcmdkc](https://miro.medium.com/max/590/1*PNTYqfrFE2d9WhVvpVZjJA.png)

Great we are ready to write some code!!

9. Go back into `cronGit` directory using `cd ..`

10. Open `index.py` with and add the following code at the very top of the file

```bash
from git import Repo
```

Here we import the PythonGit module that will help us easily execute common git commands.

11. Set up general variables right beneath the top import statement like so:

```bash
working_tree_dir = '/Users/Ospiegel/Development/cronGit/autoGitActivity'
file = "autoGitActivity/activityTracker.txt"
repo = Repo(working_tree_dir)
```

**working_tree_dir**: The absolute path/location of the repository you just initialized in step 7, the one you would like to auto-push.

**file**: file will be the path to the text file we will add lines for the sake of demonstration

**repo**: repo is actually a Repo class object that comes with the GitPython module we imported that takes a path as an argument as shown above.

12. Write simple function that will slightly alter the text file we created

```python
def alter_file(file):
    with open(file, "a") as f:
        f.write("new line\n")
```

The function will take in a file path to a text file (as a string) and write a new line in it with the text ‘new line’ (how original).

13. Write a function that will execute git add, commit, and push commands in the repository we previously set up

```python
def git_activities(repo):
    if len(repo.untracked_files):    
        repo.git.add(A=True)
        repo.git.commit('-m', 'initial commit')
        repo.git.push('origin', 'HEAD:refs/for/master')
```

The

function accepts a Repo object (like the one we already declared) and first checks to see if there are any untracked files. If there are, it will stage (add) all changes/additions, subsequently it will commit with a message, and finally it will push to the master.

14. Now we simply invoke the functions we wrote at the bottom of the file

```python
alter_file(file)

git_activities(repo)
```

We can save and exit our python script.

15. Now let’s open a new terminal window and once again type `crontab -e`

16. Press `i` to edit

We would like to add a command that will run this python script we just wrote, sounds easy enough right?

Well not so fast!

Our python script has extra dependancies and we have to run this command through the virtual environment we set up. To do this we will use this chained command:

```bash
SHELL=/bin/bash
* * * * * cd development/cronGit/venv && source bin/activate && cd .. && python index.py
```

 -   * * * * * five stars separated by spaces indicate that will run this every minute, every hour, every day, every month, at any day of the week…
 -   Then we have a chained command that is separated with `&&`
 -   First tread into the virtual environment location:
    `cd development/cronGit/venv`
 -   Activate the venv: `source bin/activate`
 -   Tread one back out of the venv location back into where we saved our index.py file: `cd ..`
 -   Lastly run our pythin script : `python index.py`

After pasting the command into the crontab; it should look like this:

![dcdcd](https://miro.medium.com/max/700/1*0247pQ0DbMMRqEMlY4KV_A.png)

You may now press esc and then follow it up with typing `:wq` to exit

OK you’re all set up!
You now look like a super active git user, who commits and pushes every minute of the day. You also learnt about crontab recurring commands, and maybe a thing or two about the GitPython module.

link to git repo [here](https://github.com/ospiegel91/cronGit)