如何使用libgit2sharp获取以前版本的文件

我正在尝试使用libgit2sharp来获取文件的先前版本。 我希望工作目录保持原样,至少恢复到以前的状态。

我最初的方法是尝试存储,检查我想要的文件的路径,将其保存到字符串变量,然后存储弹出窗口。 有没有办法存放流行音乐? 我很难找到它。 这是我到目前为止的代码:

  using (var repo = new Repository(DirectoryPath, null)) { var currentCommit = repo.Head.Tip.Sha; var commit = repo.Commits.Where(c => c.Sha == commitHash).FirstOrDefault(); if (commit == null) return null; var sn = "Stash Name"; var now = new DateTimeOffset(DateTime.Now); var diffCount = repo.Diff.Compare().Count(); if(diffCount > 0) repo.Stashes.Add(new Signature(sn, "x@y.com", now), options: StashModifiers.Default); repo.CheckoutPaths(commit.Sha, new List{ path }, CheckoutModifiers.None, null, null); var fileText = File.ReadAllText(path); repo.CheckoutPaths(currentCommit, new List{path}, CheckoutModifiers.None, null, null); if(diffCount > 0) ; // stash Pop? } 

如果有一种比使用Stash更简单的方法,那也会很有效。

有没有办法存放流行音乐? 我很难找到它

不幸的是, Stash pop需要在libgit2中不可用的合并。

我正在尝试使用libgit2sharp来获取文件的先前版本。 我希望工作目录保持原样

您可以通过打开同一存储库的两个实例来实现此类结果,每个实例指向不同的工作目录。 Repository构造函数接受RepositoryOptions参数,该参数应允许您执行此操作。

以下代码演示了此function。 这将创建一个附加实例( otherRepo ),您可以使用该实例检索当前在主工作目录中检出的文件的不同版本。

 string repoPath = "path/to/your/repo"; // Create a temp folder for a second working directory string tempWorkDir = Path.Combine(Path.GetTempPath(), "tmp_wd"); Directory.CreateDirectory(newWorkdir); // Also create a new index to not alter the main repository string tempIndex = Path.Combine(Path.GetTempPath(), "tmp_idx"); var opts = new RepositoryOptions { WorkingDirectoryPath = tempWorkDir, IndexPath = tempIndex }; using (var mainRepo = new Repository(repoPath)) using (var otherRepo = new Repository(mainRepo.Info.Path, opts)) { string path = "file.txt"; // Do your stuff with mainrepo mainRepo.CheckoutPaths("HEAD", new[] { path }); var currentVersion = File.ReadAllText(Path.Combine(mainRepo.Info.WorkingDirectory, path)); // Use otherRepo to temporarily checkout previous versions of files // Thank to the passed in RepositoryOptions, this checkout will not // alter the workdir nor the index of the main repository. otherRepo.CheckoutPaths("HEAD~2", new [] { path }); var olderVersion = File.ReadAllText(Path.Combine(otherRepo.Info.WorkingDirectory, path)); } 

通过查看RepositoryOptionFixture中运行它的测试,您可以更好地掌握此RepositoryOptions类型。