Find the relative git directory.
19512
public function getGitDir(): string
    {
        $gitDir = $this->config->getGitDir();
        if (!$this->fileSystem->exists($gitDir)) {
            throw new RuntimeException('The configured GIT directory could not be found.');
        }

        return $this->getRelativePath($gitDir);
    }
531267
@Nullable
  private File findProjectGitDirectory() {
    if (this.mavenProject == null) {
      return null;
    }

    File basedir = mavenProject.getBasedir();
    while (basedir != null) {
      File gitdir = new File(basedir, Constants.DOT_GIT);
      if (gitdir.exists()) {
        if (gitdir.isDirectory()) {
          return gitdir;
        } else if (gitdir.isFile()) {
          return processGitDirFile(gitdir);
        } else {
          return null;
        }
      }
      basedir = basedir.getParentFile();
    }
    return null;
  }
774108
def is_git(path):
    """"""
    try:
        repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')
        return True if repo_dir else False
    except (OSError, RuntimeError):
        return False
1128946
def is_git_directory_clean(path_to_repo: Path,
                           search_parent_dirs: bool = True,
                           check_untracked: bool = False) -> None:
    
    repo = Repo(str(path_to_repo), search_parent_directories=search_parent_dirs)
    logger.debug("is_git_directory_clean check for repo in path={} from "\
                  "cwd={} with search_parent_directories={}".format(
                        path_to_repo, os.getcwd(), search_parent_dirs))

    # If there are changes to already tracked files
    if repo.is_dirty():
        raise DirtyRepoException("Changes to the index or working tree."
                                 "Commit them first .")
    if check_untracked:
        if repo.untracked_files:
            raise DirtyRepoException("Untracked files. Commit them first.")
607387
def rm(pattern):
    """"""
    paths = glob.glob(pattern)
    for path in paths:
        if path.startswith('.git/'):
            continue
        if os.path.isdir(path):
            def onerror(fun, path, excinfo):
                exc = excinfo[1]
                if exc.errno != errno.ENOENT:
                    raise

            safe_print("rmdir -f %s" % path)
            shutil.rmtree(path, onerror=onerror)
        else:
            safe_print("rm %s" % path)
            os.remove(path)
87938
function getGitFolderPath(currentPath) {
  var git = path.resolve(currentPath, '.git')

  if (!exists(git) || !fs.lstatSync(git).isDirectory()) {
    console.log('pre-commit:');
    console.log('pre-commit: Not found .git folder in', git);
    
    var newPath = path.resolve(currentPath, '..');

    // Stop if we on top folder
    if (currentPath === newPath) {
      return null;
    }

    return getGitFolderPath(newPath);
  }

  console.log('pre-commit:');
  console.log('pre-commit: Found .git folder in', git);
  return git;
}
100150
def check_git():
    """"""
    try:
        with open(os.devnull, "wb") as devnull:
            subprocess.check_call(["git", "--version"], stdout=devnull, stderr=devnull)
    except:
        raise RuntimeError("Please make sure git is installed and on your path.")
775822
def _get_relative_path(self):
    """"""
    param_string = self._get_query_string()
    if self.path is None:
      path = '/'
    else:
      path = self.path
    if param_string:
      return '?'.join([path, param_string])
    else:
      return path
246212
def find_repositories_with_locate(path):
    """"""
    command = [b'locate', b'-0']
    for dotdir in DOTDIRS:
        # Escaping the slash (using '\/' rather than '/') is an
        # important signal to locate(1) that these glob patterns are
        # supposed to match the full path, so that things like
        # '.hgignore' files do not show up in the result.
        command.append(br'%s\/%s' % (escape(path), escape(dotdir)))
        command.append(br'%s\/*/%s' % (escape(path), escape(dotdir)))
    try:
        paths = check_output(command).strip(b'\0').split(b'\0')
    except CalledProcessError:
        return []
    return [os.path.split(p) for p in paths
            if not os.path.islink(p) and os.path.isdir(p)]
77896
function findFilesToPackage(dir, callback) {
    var cwd = process.cwd();
    process.chdir(dir);

    var gitls = spawn('git', ['ls-files']),
        // This gets the full path to each file in each submodule
        subls = spawn('git', ['submodule', 'foreach', 'for file in `git ls-files`; do echo "$path/$file"; done']);
        // List all node_modules
        modls = spawn('find', ['node_modules']);


    var mainFileList = '';
    gitls.stdout.on('data', function (data) {
        mainFileList += data;
    });
    gitls.on('exit', returnFileList);

    var subFileList = '';
    subls.stdout.on('data', function (data) {
        subFileList += data;
    });
    subls.on('exit', returnFileList);
    
    var modFileList = '';
    modls.stdout.on('data', function (data) {
        modFileList += data;
    });
    modls.on('exit', returnFileList);

    var lsCount = 0;
    function returnFileList(code) {
        lsCount++;
        if (lsCount < 3) {
            return;
        }
        process.chdir(cwd);

        // Convert \n separated list of filenames into a sorted array
        var fileList = (mainFileList.trim() + '\n' + subFileList.trim() + '\n' + modFileList.trim()).split('\n').filter(function(file) {
            // Ignore entering submodule messages
            if (file.indexOf('Entering ') === 0) {
                return;
            }

            // Ignore hidden and backup files
            if (file.split('/').pop()[0] == '.' || file[file.length - 1] == '~') {
                return;
            }

            // Submodules appear in ls-files but aren't files. Skip them
            if (fs.statSync(path.join(dir, file)).isDirectory()) {
                return;
            }

            
            return file;
        }).sort();

        callback(fileList);
    }

}
66357
def git_working_dir(func):
    """"""

    @wraps(func)
    def set_git_working_dir(self, *args, **kwargs):
        cur_wd = os.getcwd()
        os.chdir(self.repo.working_tree_dir)
        try:
            return func(self, *args, **kwargs)
        finally:
            os.chdir(cur_wd)
        # END handle working dir
    # END wrapper

    return set_git_working_dir
275848
protected function getGitDirectory()
    {
        if ($this->gitDirectory === null) {
            $this->gitDirectory = $this->getWorktreeDirectory() . '/.git';
        }

        return $this->gitDirectory;
    }
333987
def find_hwpack_dir(root):
    """"""
    root = path(root)
    log.debug('files in dir: %s', root)
    for x in root.walkfiles():
        log.debug('  %s', x)

    hwpack_dir = None
    for h in (root.walkfiles('boards.txt')):
        assert not hwpack_dir
        hwpack_dir = h.parent
        log.debug('found hwpack: %s', hwpack_dir)

    assert hwpack_dir
    return hwpack_dir
90881
function resolveGitRoot(filepath) {
    var relativeToGit, repoId;

    // No git repo cloned, or file is not in a git repository
    if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null;

    // Extract first directory (is the repo id)
    relativeToGit = path.relative(GIT_TMP, filepath);
    repoId = _.first(relativeToGit.split(path.sep));
    if (!repoId) return;

    // Return an absolute file
    return path.resolve(GIT_TMP, repoId);
}
364539
def find_config(revision):
    """"""
    if not is_git_repo():
        return None

    cfg_path = f"{revision}:.cherry_picker.toml"
    cmd = "git", "cat-file", "-t", cfg_path

    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        path_type = output.strip().decode("utf-8")
        return cfg_path if path_type == "blob" else None
    except subprocess.CalledProcessError:
        return None
974686
def find_submodule_git_dir(d):
    """"""
    if is_git_dir(d):
        return d

    try:
        with open(d) as fp:
            content = fp.read().rstrip()
    except (IOError, OSError):
        # it's probably not a file
        pass
    else:
        if content.startswith('gitdir: '):
            path = content[8:]

            if Git.is_cygwin():
                ## Cygwin creates submodules prefixed with `/cygdrive/...` suffixes.
                path = decygpath(path)
            if not osp.isabs(path):
                path = osp.join(osp.dirname(d), path)
            return find_submodule_git_dir(path)
    # end handle exception
    return None
277310
def relative_path(self, absolute_path, output_filename):
        """"""
        absolute_path = posixpath.join(settings.PIPELINE_ROOT, absolute_path)
        output_path = posixpath.join(settings.PIPELINE_ROOT, posixpath.dirname(output_filename))
        return relpath(absolute_path, output_path)