final RevWalk revWalk = new RevWalk( repo );
final ObjectId[] commits = resolveObjectIds( git, _commits );
if ( _commits.length != commits.length ) {
throw new IOException( "Couldn't resolve some commits." );
}
try {
final Ref headRef = getBranch( git, targetBranch );
newHead = revWalk.parseCommit( headRef.getObjectId() );
// loop through all refs to be cherry-picked
for ( final ObjectId src : commits ) {
final RevCommit srcCommit = revWalk.parseCommit( src );
// get the parent of the commit to cherry-pick
if ( srcCommit.getParentCount() != 1 ) {
throw new IOException( new MultipleParentsNotAllowedException(
MessageFormat.format(
JGitText.get().canOnlyCherryPickCommitsWithOneParent,
srcCommit.name(),
Integer.valueOf( srcCommit.getParentCount() ) ) ) );
}
final RevCommit srcParent = srcCommit.getParent( 0 );
revWalk.parseHeaders( srcParent );
final RevCommit revCommit = revWalk.parseCommit( src );
final RefUpdate ru = git.getRepository().updateRef( "refs/heads/" + targetBranch );
if ( newHead == null ) {
ru.setExpectedOldObjectId( ObjectId.zeroId() );
} else {
ru.setExpectedOldObjectId( newHead );
}
ru.setNewObjectId( src );
ru.setRefLogMessage( reflogPrefix + " " + srcCommit.getShortMessage(), false );
final RefUpdate.Result rc = ru.forceUpdate();
switch ( rc ) {
case NEW:
case FORCED:
case FAST_FORWARD:
newHead = revCommit;
break;
case REJECTED:
case LOCK_FAILURE:
throw new ConcurrentRefUpdateException( JGitText.get().couldNotLockHEAD, ru.getRef(), rc );
default:
throw new JGitInternalException( MessageFormat.format( JGitText.get().updatingRefFailed, Constants.HEAD, src.toString(), rc ) );
}
}
} catch ( final java.io.IOException e ) {
throw new IOException( new JGitInternalException(
MessageFormat.format(
JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
e ), e ) );
} catch ( final Exception e ) {
throw new IOException( e );
} finally {
revWalk.release();
}
}