pythongitgitpython

Get list of directories and files in git repo using Python


I want to fetch all files and directories present in a git repo using Python and then parse through each directory to get details of files present under them.

Below is the piece of code I have been trying but it returns nothing. I am able to get branch details.

import git
import os
from git import Repo

Repo.clone_from(repo_url,local_path)
repo = git.Repo(local_path)
remote = repo.remote("origin")

for branches in remote.refs:
 //code to get a specific branch, say abc, using if condition

repo.git.checkout(abc)
os.listdir(local_path)

Solution

  • Here's one example:

    import git
    import os
    
    # Clone the repository
    repo_url = "https://github.com/your_username/your_repository.git"
    local_path = "path_to_local_clone"
    git.Repo.clone_from(repo_url, local_path)
    
    # Switch to a specific branch
    repo = git.Repo(local_path)
    repo.git.checkout("master")
    
    # List files and directories in the repository
    contents = os.listdir(local_path)
    
    for item in contents:
        item_path = os.path.join(local_path, item)
    
        if os.path.isfile(item_path):
            print(f"File: {item}")
        elif os.path.isdir(item_path):
            print(f"Directory: {item}")