how to retrieve list of local git repos via libgit2sharp?

691 views Asked by At

Via libgit2sharp how to obtain a list of local repos?

I don't see anything useful in the list of git commands

https://github.com/libgit2/libgit2sharp/wiki/LibGit2Sharp-Hitchhiker%27s-Guide-to-Git

3

There are 3 answers

2
nulltoken On

via libgit2sharp how to obtain a list of local repos ?

LibGit2sharp is a library that allows users to interact with git repositories.

However, it doesn't provide any feature which would scan the filesystem, searching for potentially existing local repositories.

0
Mike de Klerk On

This worked for me to find the list of repositories inside a directory (non-recursive) using libgit2sharp.

Usage example:

var gitService = new GitService();
var repositoryPaths = gitService.FindRepositoryPaths(rootDirectory);

public class GitService
{
    private const string GitRepoFolder = ".git";

    public IEnumerable<string> FindRepositoryPaths(string path)
    {
        var repositories = new List<string>();

        var directories = Directory.EnumerateDirectories(path);
        foreach(var directory in directories)
        {
            var possibleGitDirectory = Path.Combine(directory, GitRepoFolder);
            if (Directory.Exists(possibleGitDirectory))
            {
                try
                {
                    using (var repo = new Repository(directory))
                    {
                        if (repo != null)
                        {
                            repositories.Add(directory);
                        }
                    }
                } 
                catch(RepositoryNotFoundException)
                {

                }
            }
        }

        return repositories;
    }
}
0
Roger Hill On

If you are actually asking about branches in an enlistment:

    public List<string> GetLocalBranchList()
    {
        var output = new List<string>();

        using (var repo = new Repository(_LocalGitPath))
        {
            foreach (var branch in repo.Branches)
                output.Add(branch.FriendlyName);

            return output;
        }
    }

if you are truly meaning repros and not branches, then no. But you don't really need libgit2sharp for that. Just scan all the directories for some of the files or folders that are present in each enlistment (the .git hidden folder, .gitignore, etc.)