在使用libgit2sharp到临时目录的提交时检出子模块

时间:2018-01-08 22:00:56

标签: c# libgit2sharp

我尝试了以下操作,但返回的提交为null。如果我使用mainRepo请求提交,那么它已填充而不是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);
      }
    }
}

1 个答案:

答案 0 :(得分:1)

感谢@Edward Thompson领导的方式。

您可以使用Submodule IndexCommitId获取正确的提交ID,并使子模块与主存储库保持同步。

    // 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);
      }
    }