gpt4 book ai didi

java - 使用 JGit 计算文件的提交次数

转载 作者:行者123 更新时间:2023-12-01 12:55:08 25 4
gpt4 key购买 nike

我正在尝试使用 Java 按提交次数列出 git 存储库中存在的所有文件。为此,我使用 JGit 库。

String filename = "/a/b/c.java";
String localPath = localPath;
Repository localRepo = new FileRepository(localPath + "/.git");
Git git = new Git(localRepo);
ObjectId head = localRepo.resolve(Constants.HEAD);
Iterable<RevCommit> logs = git.log().add(head).addPath(filename).call();
for (RevCommit revCommit : logs) {
count++;
}

但是,我得到的 count 始终为 0

当我使用存储库主目录中现有的文件时,我得到正确的答案:

String filename = "d.java";
String localPath = localPath;
Repository localRepo = new FileRepository(localPath + "/.git");
Git git = new Git(localRepo);
ObjectId head = localRepo.resolve(Constants.HEAD);
Iterable<RevCommit> logs = git.log().add(head).addPath(filename).call();
for (RevCommit revCommit : logs) {
count++;
}

但是,即使我更改到包含 c.java 的目录,我仍然没有得到正确的答案:

String filename = "c.java";
String localPath = localPath;
Repository localRepo = new FileRepository(localPath + "/.git");
Git git = new Git(localRepo);
ObjectId head = localRepo.resolve(Constants.HEAD);
System.setProperty("user.dir", localPath + "a/b";
Iterable<RevCommit> logs = git.log().add(head).addPath(filename).call();
for (RevCommit revCommit : logs) {
count++;
}

有人可以帮助我理解我做错了什么吗?

最佳答案

您的代码片段不显示提交是如何创建的/存储库处于哪种状态。不过,可以肯定的是:像上一个代码片段中那样设置系统属性 user.dir 是没有用的,它不会被 JGit 评估。

以下内容并不完全是答案,而是一个如何将 git log 限制为文件夹中特定文件的工作示例。使用最新版本的 JGit 运行代码会成功。

public class LogLearningTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();

private Git git;
private File file;

@Test
public void testCountNumberOfCommitsOnFile() throws Exception {
writeFile( "initial content" );
commitAll( "Create file in folder" );
commitAll( "Unrelated commit" );
writeFile( "changed content" );
commitAll( "Change file in folder" );
git.commit().setMessage( "Other commit" ).call();

Iterable<RevCommit> logs = git.log().addPath( "folder/file" ).call();
int count = 0;
for( RevCommit revCommit : logs ) {
count++;
}

assertEquals( 2, count );
}

@Before
public void setUp() throws GitAPIException {
git = Git.init().setDirectory( tempFolder.getRoot() ).call();
File folder = new File( git.getRepository().getWorkTree(), "folder" );
folder.mkdir();
file = new File( folder, "file" );
}

@After
public void tearDown() {
git.getRepository().close();
}

private void writeFile( String content ) throws IOException {
FileOutputStream outputStream = new FileOutputStream( file );
outputStream.write( content.getBytes( "UTF-8" ) );
outputStream.close();
}

private void commitAll( String message ) throws GitAPIException {
git.add().addFilepattern( "." ).call();
git.commit().setMessage( message ).call();
}

}

关于java - 使用 JGit 计算文件的提交次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23973284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com