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

Asked

Viewed 53 times

2

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

Follows 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);

}

2 answers

2


You can use:

Repository.IsValid(dir);

The source code of the class Repository is here

Freely translating the text of the method documentation, we have the following:

Checks whether the parameter path indicates a valid Git repository.

Parameters:

path: The path to the git repository to check can be either the path to a git directory (for nonempty repositories it would be the ".git" directory inside the working directory) or the path to the working directory.

Returns:

true if the repository can be solved by this way; false otherwise

  • 1

    Thanks, it worked perfectly!

  • 1

    I improved the answer by inserting the text of the documentation, so that it is for future references.

1

Apparently the command is used git-ls-tree. If there’s 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.");
}
  • Thanks Gypsy, but Marcus' answer is better, anyway, one question I have is about this "sha" that’s a constant value, or name of my commit? I saw it in their documentation but I didn’t understand.

  • Actually the other answer is better. "sha" would be the Commit Id, from what I understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.