Check if directory is a repository with LibGit2Sharp (C #)

2

I'm starting to study C # so my knowledge is quite limited. I'm using the LibGit2Sharp library and would like to check if an informed directory is a repository. Their documentation is not yet complete, so I'm having trouble.

Follow my code:

static void SetRepository()
{
    bool seted = false;
    do
    {
        Console.WriteLine("Informe o caminho do repositório:");
        String dir = Console.ReadLine();
        EmptyLine();

        // Talvez a verificação devesse ser aqui... Mas não sei como descobrir se é um repositório GIT ou não
        if (!System.IO.Directory.Exists(dir.Trim())
        {
            Console.WriteLine("Diretório inválido.");
            EmptyLine();
            Pause();
        }
        else
        {
            // Não estou sabendo como verificar se é um repositório aqui!!
            SetArg("repository", dir);
            repo = new Repository(dir);
            seted = true;

        }

    } while (!seted);

}
    
asked by anonymous 11.05.2015 / 15:13

2 answers

2

You can use:

Repository.IsValid(dir);

The source code for class Repository is here

By freely translating the text from the method documentation, we have the following:

  

Checks whether the path parameter indicates a valid Git repository.

     

Parameters :

     

path : The git repository path to check may be either the path to a git directory (for non-empty repositories it would be the ".git" directory within the working directory) or the path to the working directory .

     

Returns :

     

true if the repository can be resolved by this path; false otherwise

    
11.05.2015 / 15:34
1

The git-ls-tree command appears to be used. If there is something inside, it's a repository:

using (var repo = new Repository(dir))
{
    var tree = Repository.Lookup<Tree>("sha");
    if (tree != null && tree.items.Count > 0)
        Console.WriteLine("É um repositório.");
}
    
11.05.2015 / 15:34