Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fralau
Last active April 11, 2018 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fralau/553acb94040a9408a8935fb5e81b26c9 to your computer and use it in GitHub Desktop.
Save fralau/553acb94040a9408a8935fb5e81b26c9 to your computer and use it in GitHub Desktop.
Python: know whether the current directory is part of a git repo

How to know wether current directory is part of a git repo

Idea

The git rev-parse command returns 0 if the current directory is in a git repo and an error code otherwise. It is thus necessary to call the bash command, suppressing stdout and stderr, in order to get the return code.

Code

import os, subprocess
def is_git_repo():
    "Check whether this is a git repo"
    # we use the exit code
    with open(os.devnull, "w") as d:
        return not bool(subprocess.call('git rev-parse', shell=True,
                        stdout=d, stderr=d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment