Anu Chawla Anu Chawla - 28 days ago 6
Git Question

addFilePattern does not throw FileNotFoundException if file to be added is not present

I have written a java program to push to a git repository where I am pushing specific files at a time instead of pushing all files.

try {
} catch (Exception e) {

But if
is not present, the catch block is not entered.
If I do the same thing with CLI Git, it gives exception as

fatal: pathspec 'D:\mygit\files\\file1.txt' did not match any files

I want to catch this exception in Java using JGit.

JGit version 4.6.0, Java 1.8, Windows 10

Answer Source

JGit does not consider it as an error to pass a non-existing path addFilepatern(). The reason, therefore, could be that the method also accepts a file name pattern. And such a pattern may or may not match files.

You will have to check the existence of the file yourself. Either with the Java file API, for example

boolean fileExists = new File( repository.getWorkTree(), "file.txt" ).isFile();

Or through the DirCache returned from AddCommand::call(), for example

DirCache dirCache = git.add().addFilePattern( "file.txt" ).call();
boolean fileExists = dircache.findEntry( "file.txt" ) >= 0;