如果Jgit clone命令失败,如何删除已创建的目录?

问题描述 投票:0回答:1

我已经编写了一个简单的函数来使用Jgit CloneCommand克隆存储库。它工作正常。但是,如果克隆过程因任何原因(如用户名或密码错误)而失败,则无法删除在此过程中创建的本地目录。因为文件夹包含一个活动的Git存储库。

我试过“cloneCommand.getRepository()。close();”在catch块中,它给出了NullPointerException

File file = new File(localDirectory("Files/Application"));

CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI(repo.getUrl());
        cloneCommand.setDirectory(file);
cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repo.getUsername(), repo.getPassword()));
try {
    cloneCommand.call();
} catch (GitAPIException e) {
    if (file.exists()) {
            file.delete();
    }
}
java clone jgit
1个回答
0
投票

您需要以正确的顺序递归删除文件。有些文件很快就会丢失(比如git locks文件),所以只有在文件仍然存在的情况下才需要删除。

Git实现AutoCloseable,因此它应该与try-with-resources语句一起使用。

我会做这样的事情:

try (Git git = Git.cloneRepository()
    .setDirectory(file)
    .call()) {
} catch (GitAPIException e) {
    Files.walkFileTree(file.toPath(), new DeleteFileVisitor())
}

DeleteFileVisitor.java

public class DeleteFileVisitor extends SimpleFileVisitor<Path> {

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes basicFileAttributes) throws IOException {
        Files.deleteIfExists(file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException {
        Files.deleteIfExists(directory);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exception) {
        // log error
        return FileVisitResult.CONTINUE;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.