Capturing file contents with GitWorkTree APIs

For cases of PR merge conflicts I would like to capture the contents of conflicted files, including the conflict markers. I am able to perform a merge with WorkTree APIs to put the worktree into a merging state and add conflict markers to files. However, I can’t find a way to capture the contents of these conflicted files.

Since the WorkTree APIs don’t provide the location of the worktree, there seems to be no way to use Java IO to access the files. Also, I don’t seem to be able to use ContentService methods to access the contents of the conflicted files since they are not in the repository.

With the new WorkTree APIs, how can I capture the contents of a file in the worktree?

1 Like

Hi Tim,

Unfortunately the WorkTree API does not currently provide a way to read content from the work tree. We explored adding it when we introduced the WorkTree API but decided to hold of on introducing until we get a good use case for because it’s (a bit) more complicated than it looks at first.

For background, we use a sparse checkout to create the work tree on disk, which means that only the files that are modified/added in the index actually exist on disk. For most git operations this is transparent, but for a generic “read” WorkTree method it would require us to do a bit more work to ensure the file exists in the work tree on disk and check it out if it does not.

Since the WorkTree APIs don’t provide the location of the worktree, there seems to be no way to use Java IO to access the files. Also, I don’t seem to be able to use ContentService methods to access the contents of the conflicted files since they are not in the repository.

With Mesh, the work trees will be created on a remote Mesh node and therefore not accessible using Java IO at all (which is why we don’t expose the path on disk).

With the new WorkTree APIs, how can I capture the contents of a file in the worktree?

We might still add it to the WorkTree API, but for now a workaround could be to commit the merge complete with the conflict markers in the files (git add <paths-with-conflicts> followed by a git commit), and then use git cat-file (workTree.builder().catFile()) to read back the files. As long as you don’t publish those changes to the repository, you should be good.

Kind regards,
Michael Heemskerk
Atlassian Bitbucket