'Python - how to check whether the path is under a git repo? and extract the repo name

I'm trying to develop a Gatekeeping script in python rollin.py with the following requirements:

  1. Assume user would launch the rollin.py script from anywhere within his local git cloned area to push his commits to the master repo

  2. Now, rollin.py script would

    • clone a repo from master
    • pull user commits and merges into the cloned repo
    • Run the compliance tests
    • If passes, then push those changes to master repo else discard and notify the user

Now within rolloin.py script, how would I check the the repo name and user's git clone path? (since user can launch the rolloin.py script from anywhere in his local area)

Is there any existing function or method available? otherwise I'm thinking to implement reverse recursive search from cwd to locate the .git and and then url from it's config file.



Solution 1:[1]

Using the GitPython library

You can achieve this with the already authored GitPython module. Read the docs.

$ pip install GitPython

Python snippet to print the base git path and the origin remote url.

import git
    
# Raises InvalidGitRepositoryError when not in a repo
repo = git.Repo(".", search_parent_directories=True) 
print "Location "+ repo.working_tree_dir
print "Remote: " + repo.remote("origin").url

To create a new git repo

import git 
    
newRepo = git.Repo.init("my-git-repo", mkdir=True)

Solution 2:[2]

You could use os.system to run git rev-parse --git-dir, which will return the path to the .git folder of the repository in which the command is run. For more info, see How to find the path of the local git repository when I am possibly in a subdirectory

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alper
Solution 2 Ari Lotter