Usage of git worktrees with libgit2sharp to clone and checkout existing repos with several branches

Viewed 233

I want to write a C# Program that devs can use to clone several git repos with worktrees added. So my main idea is do use libgit2sharp to clone e.g. a master, and add a worktree with the checked out "develop" branch (that already exists)

I haven't found much information of how to use the Worktree feature - when I use a .bat I remember that there seems to be (has been?) a limitation that if I want to add a worktree I must have had that branch already locally or a branch would be created locally with the same name.

Basically something along the lines of:

cd C:\gittryout\testrepo\
git clone REPO master
cd master
//to cicumvent creating a local branch develop if it hasn't been checked out already
git checkout develop
git checkout master
git worktree add --checkout ../develop develop

which would give me

C:\gittryout\testrepo\master (with master)
C:\gittryout\testrepo\develop (with develop)

my code at the moment looks something along those lines:

public void TryToCloneWithWorktree()
{
  string Username = "acorrectusername";
  string Password = "acorrectpw";
  string RepositoryUrl = @"path/to/git/testrepo";

  var co = new CloneOptions();
  co.CredentialsProvider = new CredentialsHandler(
                    (url, usernameFromUrl, types) =>
                    new UsernamePasswordCredentials()
                    {
                      Username = Username,
                      Password = Password
                    }
                    );
  co.BranchName = "master";
  string RepositoryPath = @"C:\gittryout\testrepo\master";
  string WorktreePath = @"C:\gittryout\testrepo\develop";
  string WorktreeSHA1 = "develop";
  using (var repo = new Repository())
  {
    Repository.Clone(RepositoryUrl, RepositoryPath, co);
    repo.Worktrees.Add(WorktreeSHA1, WorktreeSHA1, WorktreePath, false);
  }
}

but after this runs, the clone is correct (with branch master), and in there resides a shortcut _git2_a40776 with target .\testing

Do I need to clone the worktree added too, or how can I achieve what the bat did in C# with libgit2sharp?

br

0 Answers
Related