我试图通过提交次数使用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
。
当我使用repo主目录中存在的文件时,我得到了正确答案:
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++;
}
有人可以帮我理解我做错了吗?
答案 0 :(得分:1)
您的代码段未显示提交的创建方式/存储库的状态。但是,有一个是肯定的:在最后一个片段中设置系统属性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();
}
}
答案 1 :(得分:0)
错误在于:
String filename = "/a/b/c.java";
尝试使用存储库相对路径(假设a
是存储库根目录中的目录):
String filename = "a/b/c.java";