added ExtendedGit.normalize method

This commit is contained in:
Brian Long 2020-12-09 22:09:31 -05:00
parent 549e95cd25
commit 388cdb2d15

View File

@ -1,5 +1,6 @@
package me.brianlong.git;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
@ -13,9 +14,15 @@ import java.util.regex.Pattern;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.api.ResetCommand.ResetType;
import org.eclipse.jgit.api.errors.CheckoutConflictException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRefNameException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
@ -55,6 +62,38 @@ public class ExtendedGit extends CachedGit {
return matcher.group(9);
}
/**
* Creates a local branch, if one does not already exist.
* Checks out the repository, targeting the remote branch.
* Resets the local branch up to the remote branch.
*/
public Ref normalize(String localBranchName, String exactRemoteBranchName)
throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, CheckoutConflictException, GitAPIException, IOException {
Ref localRef = this.getRepository().exactRef(Constants.R_HEADS + localBranchName);
if (localRef == null) {
localRef = this.branchCreate()
.setUpstreamMode(SetupUpstreamMode.NOTRACK)
.setName(localBranchName)
.setStartPoint(exactRemoteBranchName)
.call();
}
Ref checkoutRef = this.checkout()
.setName(localBranchName)
.setStartPoint(exactRemoteBranchName)
.call();
if (!localRef.getObjectId().getName().equals(checkoutRef.getObjectId().getName())) {
this.logger.warn("A checkout did not move the local branch to the proper commit; performing reset: " + localRef.getName());
this.reset()
.setMode(ResetType.HARD)
.setRef(exactRemoteBranchName)
.call();
}
return checkoutRef;
}
/**
* This method retrieves all branches, but excludes remote branches that are tracked with a local branch.
* @return