GIT conflicts can appear by PULL, PUSH or CHECKOUT.
I need to compare the two conflicting files (the local file I assume, with the remote one).
How may I load the conflicting version of the file as a string?
The current repository may use a branch.
I tried the code below, but the content is not always correct. I expect I should use something else as "head".
// call a fetch first
git.fetch().setRemote("origin").setCredentialsProvider( credentialProvider ).call();
RevCommit revCommit = git.getRepository().parseCommit(git.getRepository().resolve("head"));
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (TreeWalk treeWalk = new TreeWalk( getRepository()) ) {
treeWalk.addTree(revCommit.getTree());
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(filePath));
if (!treeWalk.next()) {
throw new IllegalStateException("Did not find expected file '" + filePath + "'");
}
final ObjectId objectId = treeWalk.getObjectId(0);
final ObjectLoader loader = getRepository().open(objectId);
loader.copyTo(os);
}
String fileAsString = bos.toString( StandardCharsets.UTF_8 );
Here is also some code showing how I catch the conflicts. I paste this for review.
By pull:
try {
MergeResult mergeResult = git.pull().setContentMergeStrategy(ContentMergeStrategy.CONFLICT).setCredentialsProvider( credentialsProvider ).call().getMergeResult();
if ( !mergeResult.getConflicts().isEmpty()){
showConflicts( mergeResult.getConflicts().keySet() );
}
catch ( CheckoutConflictException ex){
showConflicts( ex.getConflictingPaths() )
}
By Checkout:
try {
git.checkout().setName( branchName ).setStartPoint("origin/" + branchName).call();
} catch ( CheckoutConflictException ex ){
showConflicts( ex.getConflictingPaths() )
}
By Push:
try {
git.push().setRemote("origin").setCredentialsProvider(git.credentialsProvider).call();
} catch ( CheckoutConflictException ex ){
showConflicts( ex.getConflictingPaths() )
}