【发布时间】:2017-07-23 14:11:36
【问题描述】:
我正在使用 jgit(版本 4.8.0.201706111038-r)将 git repo 克隆到临时目录中,并添加关闭挂钩以在终止后删除临时目录。但是,关闭挂钩无法从 .git 子目录中删除一些文件(尽管关闭了 Git 对象,根据 jgit 的要求)。
有趣的是,只有当我使用 Path API (Files.delete(<PATH>)) 时删除才会失败,但如果我使用旧的 file.delete() 删除则不会。
这是一个最小的独立示例,其唯一依赖项是 jgit 4.8.0.201706111038-r:
public static void main(String... args) throws Exception {
String gitRepo = "https://github.com/netgloo/spring-boot-samples.git";
Path localDir = Files.createTempDirectory(null);
// Clone repo
Git git = Git.cloneRepository().setURI(gitRepo).setBranch("master").setDirectory(localDir.toFile()).call();
// Print some stuff to make sure that the git repo actually works
for (RevCommit c : git.log().call()) {
System.out.println(c);
}
git.getRepository().close(); // Close all the things!
git.close(); // Close all the things!
// Delete
Files.walkFileTree(localDir, new SimpleFileVisitor<Path>() {
void safeDelete(Path p) {
try {
Files.delete(p);
} catch (Exception e) {
try {
Files.delete(p);
} catch (Exception e2) {
System.err.println("Failed to delete " + p + " due to " + e.getClass().getSimpleName() + " using Files.detlete().\nTrying toFile().delete(): " + p.toFile().delete());
}
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
safeDelete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
safeDelete(dir);
return FileVisitResult.CONTINUE;
}
});
}
输出:
...
Failed to delete C:\Users\malt\AppData\Local\Temp\7908805853015958247\.git\objects\pack\pack-9cc3ec0769e34546bb7683f4e22ef67b3c800444.idx due to AccessDeniedException using Files.detlete().
Trying toFile().delete(): true
Failed to delete C:\Users\malt\AppData\Local\Temp\7908805853015958247\.git\objects\pack\pack-9cc3ec0769e34546bb7683f4e22ef67b3c800444.pack due to AccessDeniedException using Files.detlete().
Trying toFile().delete(): true
谁能解释为什么会这样?有没有办法让 JGIT 正确关闭这些文件,以便 Files.delete() 工作?
【问题讨论】:
标签: java filesystems jgit