From 388cdb2d15177475d4b99f77ebddabcf8a9b487f Mon Sep 17 00:00:00 2001 From: Brian Long Date: Wed, 9 Dec 2020 22:09:31 -0500 Subject: [PATCH] added ExtendedGit.normalize method --- .../java/me/brianlong/git/ExtendedGit.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/main/java/me/brianlong/git/ExtendedGit.java b/src/main/java/me/brianlong/git/ExtendedGit.java index 5fba65d..e74f672 100644 --- a/src/main/java/me/brianlong/git/ExtendedGit.java +++ b/src/main/java/me/brianlong/git/ExtendedGit.java @@ -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