alebo611
alebo611

Reputation: 1280

How to convert from File to git path?

Im using jgit, log() command, and the addPath(String path) requires me to input a git compatible path, that is, a relative path like src/java/com/foo/Test.java. But what I got is a File object, that will have an absolute path of something like: c:\hello\irrelevant\myproject\src\java\com\foo\test.java. How to convert from this to the git path? Is there some handy function within jgit itself? I cant find it....

Upvotes: 1

Views: 360

Answers (1)

Rüdiger Herrmann
Rüdiger Herrmann

Reputation: 20985

You can use Path::relativize to get the relative path between the file to add and the work directory.

For example:

File workDir = git.getWorkTree(); // e.g. "/path/to/workdir"
File file = new File("/path/to/workdir/foo.txt");

Path relativePath = workDir.toPath().relativize(file.toPath());

assertEquals("foo.txt", relativePath.toString());

Upvotes: 2

Related Questions