Enchanted Code

Using Git In Python

2 minutes read

Intro

Git is an essential tool for adding version control to your code, although can be used to add version control to anything else. Python is a easy language for most to learn and simple to use, it can be used to create small scripts to large projects.

Well what happens if you want to combine Git with Python? luckily you can use a package called ‘git-interface’, which provides a way of communicating with the git application.

Disclaimer: I am the creator/maintainer of git-interface

There is also another popular alternative GitPython, however that package currently suffers from memory leaks in long running applications.

Requirements

  • Python 3.10
  • pip package git-interface 0.5.2
  • git 2.30

Install

Ok let’s first install the pip package as shown in the command below:

1
python -m pip install git-interface

Use

Now we have the package, we can write a script to clone a repository.

1
2
3
4
5
6
7
8
from pathlib import Path

from git_interface.utils import clone_repo

remote_path = "https://github.com/enchant97/python-git-interface.git"
dst_path = Path("git-interface")

clone_repo(dst_path, remote_path)

When this is run we will get the repository for the git-interface and it will be cloned into the dst_path, which is currently set to the current working directory.

Now we have a repository cloned we can also get the commit logs.

1
2
3
4
5
6
from git_interface.log import get_logs

logs = get_logs(dst_path, max_number=5)

for log in logs:
    print(log.subject)

This code will get the last 5 commits to happen in the repository cloned earlier. It will then output the subject of each commit. When I run this code I get the following output:

1
2
3
4
5
drop python 3.8 and below & use "Generic Alias Type"
incr version & update changelog
improve docstrings & typing hints
fix regex
fix/update readme & badges

Let’s also access one of the files in the repository tree.

1
2
3
4
from git_interface.show import show_file

readme_content = show_file(dst_path, "main", "README.md").decode()
print(readme_content)

This will output the contents of the README.md file which is too large to put here, however your output should start with the output shown below:

1
# Git Interface ...

Conclusion

As you can see this package is quite useful if you wanted to use git from python. It has many more features than what was shown here.

As the creator of git-interface I made it to power my basic-git-web-interface program which is a streamlined alternative to something like Gitlab or Gitea.

References

Join The Community

Looking for more self-hosted, tech or programming content. Well this site is a good place to find all of that!

Stay informed about new posts or announcements about my apps join the community:

Want to help out? A great way of doing that is supporting me at: Buy Me A Coffee.

Comments

See Also

What Is Pip?

A Python 3 tutorial to show how to use Python's pip command...

Buy Me A Coffee