Orn Kristjansson
Orn Kristjansson

Reputation: 3485

Checkout submodule at commit using libgit2sharp to temporary directory

I tried the following, but the commit returned is null. If I ask for the commit using the mainRepo then it's filled and not null.

var sub_opts_at = new RepositoryOptions
{
  WorkingDirectoryPath = tempRootWorkDir,
  IndexPath = Path.Combine(tempRootWorkDir, "index__" + subrandomId);
};

using (var mainRepo = new Repository(repoDirectory))
{
    foreach (Submodule submodule in mainRepo.Submodules)
    {
      String subrepoPath = Path.Combine(mainRepo.Info.WorkingDirectory, submodule.Path);
      using (Repository subRepo = new Repository(subrepoPath, sub_opts_at))
      {
        Commit commit = subRepo.Lookup<Commit>("ff7e9d5fb6e20c2bec81f6c35b869867aa260a4e");
        subRepo.Reset(ResetMode.Hard, commit);
      }
    }
}

Upvotes: 0

Views: 239

Answers (1)

Orn Kristjansson
Orn Kristjansson

Reputation: 3485

Thanks to @Edward Thompson for leading the way.

You can use the Submodule IndexCommitId to get the right commit id and keep the submodule in sync with the main repository.

    // Get the submodules 
    foreach (Submodule subrepo in mainRepo.Submodules)
    {
      getSubModule(mainRepo, tempRootWorkDir, subrepo.Path, subrepo.IndexCommitId.ToString());
    }


    /// <summary>
    /// Check out a submodule to work directory
    /// </summary>
    private static void getSubModule(Repository repo, string workdir, string entryPath, string entryId )
    {
      // Checkout to the temp directory, set index options
      string subtempIndex_at = Path.Combine(workdir, "index__" + GitInteractor.GetRandomId());
      var sub_opts_at = new RepositoryOptions
      {
        WorkingDirectoryPath = Path.Combine(workdir, entryPath),
        IndexPath = subtempIndex_at
      };

      // Sub repository path in the main repo
      string subdir = Path.Combine(repo.Info.WorkingDirectory, entryPath);
      using (Repository subRepo = new Repository(subdir, sub_opts_at))
      {
        // Get the sub repo commit at the entry id, this way the repos will be 
        // in sync through time ( between main repo and sub repo )
        Commit commit = subRepo.Lookup<Commit>(entryId);
        // Hard / exact
        subRepo.Reset(ResetMode.Hard, commit);
      }
    }

Upvotes: 1

Related Questions