def _get_git_dir(git_dir=None, cwd=None):
    """
    _get_git_dir(dir=None, cwd=None) --> (git_dir, working_dir)

    Attempt to find the git directory, similarly to the way git does.
    git_dir should be the git directory explicitly specified on the command
    line, or None if not explicitly specified.

    If git_dir is not explicitly specified, the GIT_DIR environment variable
    will be checked.  If that is not specified, the current working directory
    and its parent directories will be searched for a git directory.

    Returns a tuple containing the git directory, and the default working
    directory.  (The default working directory is only to be used if the
    repository is not bare, and the working directory was not specified
    explicitly via some other mechanism.)  The default working directory
    may be None if there is no default working directory.
    """
    if cwd is None:
        cwd = os.getcwd()

    # If git_dir wasn't explicitly specified, but GIT_DIR is set in the
    # environment, use that.
    if git_dir == None and os.environ.has_key('GIT_DIR'):
        git_dir = os.environ['GIT_DIR']

    # If the git directory was explicitly specified, use that.
    # The default working directory is the current working directory
    if git_dir != None:
        if not is_git_dir(git_dir):
            raise NotARepoError(git_dir)
        return (git_dir, cwd)

    # Otherwise, attempt to find the git directory by searching up from
    # the current working directory.
    ceiling_dirs = []
    if os.environ.has_key('GIT_CEILING_DIRECTORIES'):
        ceiling_dirs = os.environ['GIT_CEILING_DIRECTORIES'].split(':')
    ceiling_dirs.append(os.path.sep) # Add the root directory

    dir = os.path.normpath(cwd)
    while True:
        # Check to see if this directory contains a .git directory
        #
        # TODO: git also accepts regular files called .git that contain
        # "gitdir: <path>"
        git_dir = os.path.join(dir, '.git')
        if os.path.isdir(git_dir):
            if is_git_dir(git_dir):
                return (git_dir, dir)

        # Check to see if this directory looks like a git directory
        if is_git_dir(dir):
            return (dir, None)

        # Walk up to the parent directory before looping again
        (parent_dir, rest) = os.path.split(dir)

        # If the parent_dir is one of the ceiling directories,
        # we should stop before examining it.  The current directory
        # does not appear to be inside a git repository.
        if parent_dir in ceiling_dirs:
            raise NotARepoError(cwd)

        dir = parent_dir
dataset/ETHPy150Open facebookarchive/git-review/src/gitreview/git/__init__.py/_get_git_dir/original