'JGit - Unable to Delete .git Directory After Cloning

I'm using the following snippet to clone a single branch of a git repository to the local filesystem using JGit:

public void cloneSource(Path dir) throws IOException {
    CloneCommand cmd = Git.cloneRepository();
    cmd.setDirectory(dir.toFile());
    cmd.setURI(repositoryUrl);
    cmd.setBranch(branchName);
    cmd.setBranchesToClone(Set.of("refs/heads/" + branchName));
    cmd.setCloneAllBranches(false);
    credentials.provideCredentials(cmd); // Sets authentication info for the command
    try {
        var git = cmd.call();
        git.getRepository().close();
        git.close();
        git.gc().call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    }
}

After cloning, though, it is impossible for Java to delete files in the .git directory of the local repository, throwing AccessDeniedException, even if I shut down my original program and start it anew, or try to delete from an entirely different Java program. No other program is using those files while I'm trying to delete them.

I've read other questions which indicate the need for multiple close() calls, which I've done in the example, but that was apparently fixed a long time ago with this bug report, but no solution found on StackOverflow has worked for me.

Alternatively, if there's no clear way to forcibly delete the files, would it also be possible to use JGit to clone the files from a specific branch of a repository, without including any of the .git directory's metadata? So just a way to copy all the files without any git information.



Solution 1:[1]

The following code snippet worked for me

CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI( "http://git.sample.git" );
        cloneCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider( "user", "pwd" ) );
        cloneCommand.setDirectory(new File("D:/Hello"));
        Git cloneGit = cloneCommand.call();
        System.out.println("Clone HEAD: " + cloneGit.log().call().iterator().next());
        cloneGit.close();
        rm(new File("D/Hello/.git"));

And the rm(File file) is a method that removes the file with all the subfolder and files inside recursively

public void rm(File f){
      if (f.isDirectory()) {
            for (File c : f.listFiles()) {
                removeRecursively(c); //recursive call
            }
        }
        f.delete();
}

If you are trying to do at later instance and deleteing multiple folders, try the option of

Git.shutdown();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 codeforHarman