GitPython show files in Commit

In this blog post, we will teach our users how they can solve one of the most common problems of gitpython show files in the commit. This problem basically shows you the list of all the files present in the git repository. Git is a service that is similar to one of the most popular websites GitHub. Git allows user to deploy their files by providing them a platform on which they can load their codes, projects, websites as well as applications. 

 

 

 

Solution of gitpython show files in the commit

This problem can be solved easily by simply writing a few lines of code in a python programming language. The codes include importing some packages as well as some functions. 

 

import git
from pathlib import Path
import sys

 

Here we are installing git to connect our account with the git directory. The next package we are importing is pathlib which basically deals with the paths of different directors in your machine. The last one is the sys package which is better known as the system package. It handles the python runtime environment. 

 

 

def list_paths(root_tree, path=Path(".")):
    for blob in root_tree.blobs:
        yield path / blob.name
    for tree in root_tree.trees:
        yield from list_paths(tree, path / tree.name)

 

 

This function mainly defines the list of paths of various files in the git directory. The files in git get stored in the form of a tree. So this function iterates each and every node of the tree to get the desired file stored in it. 

 

 

repo = git.Repo(".", search_parent_directories=True)
commit = repo.commit(sys.argv[1])
for path in list_paths(commit.tree):
    print(path)

 

 

This function returns the names of the files after committing them. We define the repo in the git.repo function and after that make a commitment to it. At last, the tree gets iterated to produce the file names. The whole code is as follows:

 

 

# importing library
import git
from pathlib import Path
import sys

# Defining function to visit each node of the tree
def list_paths(root_tree, path=Path(".")):
    for blob in root_tree.blobs:
        yield path / blob.name
    for tree in root_tree.trees:
        yield from list_paths(tree, path / tree.name)

# passing git repo and then iterating it
repo = git.Repo(".", search_parent_directories=True)
commit = repo.commit(sys.argv[1])
for path in list_paths(commit.tree):
    print(path)

 

Output

 

 

 

Also Read: What is Convolutional Neural Network and Working

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *