Search in sources :

Example 1 with Git

use of org.jenkinsci.plugins.gitclient.Git in project blueocean-plugin by jenkinsci.

the class GitUtils method fetch.

public static void fetch(final Repository repo, final StandardCredentials credential) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        FetchCommand fetchCommand = git.fetch();
        addCredential(repo, fetchCommand, credential);
        fetchCommand.setRemote("origin").setRemoveDeletedRefs(true).setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*")).call();
    } catch (GitAPIException ex) {
        if (ex.getMessage().contains("Auth fail")) {
            throw new ServiceException.UnauthorizedException("Not authorized", ex);
        }
        throw new RuntimeException(ex);
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.jenkinsci.plugins.gitclient.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) ServiceException(io.jenkins.blueocean.commons.ServiceException) FetchCommand(org.eclipse.jgit.api.FetchCommand)

Example 2 with Git

use of org.jenkinsci.plugins.gitclient.Git in project blueocean-plugin by jenkinsci.

the class GitUtils method validatePushAccess.

/**
 *  Attempts to push to a non-existent branch to validate the user actually has push access
 *
 * @param repo local repository
 * @param remoteUrl git repo url
 * @param credential credential to use when accessing git
 */
public static void validatePushAccess(@Nonnull Repository repo, @Nonnull String remoteUrl, @Nullable StandardCredentials credential) throws GitException {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        // we need to perform an actual push, so we try a deletion of a very-unlikely-to-exist branch
        // which needs to have push permissions in order to get a 'branch not found' message
        String pushSpec = ":this-branch-is-only-to-test-if-jenkins-has-push-access";
        PushCommand pushCommand = git.push();
        addCredential(repo, pushCommand, credential);
        Iterable<PushResult> resultIterable = pushCommand.setRefSpecs(new RefSpec(pushSpec)).setRemote(remoteUrl).setDryRun(// we only want to test
        true).call();
        PushResult result = resultIterable.iterator().next();
        if (result.getRemoteUpdates().isEmpty()) {
            System.out.println("No remote updates occurred");
        } else {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                if (!RemoteRefUpdate.Status.NON_EXISTING.equals(update.getStatus()) && !RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
                    throw new ServiceException.UnexpectedErrorException("Expected non-existent ref but got: " + update.getStatus().name() + ": " + update.getMessage());
                }
            }
        }
    } catch (GitAPIException e) {
        if (e.getMessage().toLowerCase().contains("auth")) {
            throw new ServiceException.UnauthorizedException(e.getMessage(), e);
        }
        throw new ServiceException.UnexpectedErrorException("Unable to access and push to: " + remoteUrl + " - " + e.getMessage(), e);
    }
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) PushResult(org.eclipse.jgit.transport.PushResult) PushCommand(org.eclipse.jgit.api.PushCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.jenkinsci.plugins.gitclient.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) ServiceException(io.jenkins.blueocean.commons.ServiceException)

Example 3 with Git

use of org.jenkinsci.plugins.gitclient.Git in project blueocean-plugin by jenkinsci.

the class GitUtils method merge.

public static void merge(final Repository repo, final String localRef, final String remoteRef) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        CheckoutCommand checkoutCommand = git.checkout();
        checkoutCommand.setCreateBranch(false);
        checkoutCommand.setName(localRef);
        checkoutCommand.call();
        Ref mergeBranchRef = repo.exactRef(remoteRef);
        MergeResult merge = git.merge().include(mergeBranchRef).setFastForward(MergeCommand.FastForwardMode.FF_ONLY).call();
        if (merge.getConflicts() != null) {
            throw new RuntimeException("Merge has conflicts");
        }
    } catch (Exception e) {
        throw new ServiceException.UnexpectedErrorException("Unable to merge: " + remoteRef + " to: " + localRef, e);
    }
}
Also used : CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) MergeResult(org.eclipse.jgit.api.MergeResult) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) GitException(hudson.plugins.git.GitException) JSchException(com.jcraft.jsch.JSchException) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) TransportException(org.eclipse.jgit.api.errors.TransportException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) Ref(org.eclipse.jgit.lib.Ref) Git(org.jenkinsci.plugins.gitclient.Git) ServiceException(io.jenkins.blueocean.commons.ServiceException)

Example 4 with Git

use of org.jenkinsci.plugins.gitclient.Git in project blueocean-plugin by jenkinsci.

the class GitUtils method validateCredentials.

/**
 *  Calls 'git ls-remote -h uri' to check if git uri or supplied credentials are valid
 *
 * @param uri git repo uri
 * @param credentials credential to use when accessing git
 * @return list of Errors. Empty list means success.
 */
static List<ErrorMessage.Error> validateCredentials(@Nonnull String uri, @Nullable StandardCredentials credentials) throws GitException {
    List<ErrorMessage.Error> errors = new ArrayList<>();
    Git git = new Git(TaskListener.NULL, new EnvVars());
    try {
        GitClient gitClient = git.getClient();
        if (credentials != null) {
            gitClient.addCredentials(uri, credentials);
        }
        gitClient.getRemoteReferences(uri, null, true, false);
    } catch (IOException | InterruptedException e) {
        logger.error("Error running git remote-ls: " + e.getMessage(), e);
        throw new ServiceException.UnexpectedErrorException("Failed to create pipeline due to unexpected error: " + e.getMessage(), e);
    } catch (IllegalStateException | GitException e) {
        logger.error("Error running git remote-ls: " + e.getMessage(), e);
        if (credentials != null) {
            // this turn very hackhish with upgrade of git plugin as there is more and more and more cause/layers before having the real cause...
            if (e instanceof IllegalStateException || e.getMessage().endsWith("not authorized") || e.getMessage().endsWith("not authenticated") || (e instanceof GitException && checkCauseNotAuthenticated((GitException) e))) {
                errors.add(new ErrorMessage.Error("scmConfig.credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), "Invalid credentialId: " + credentials.getId()));
            } else {
                errors.add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage()));
            }
        } else if (e.getMessage().contains("Authentication is required") || e.getMessage().contains("connection is not authenticated")) {
            errors.add(new ErrorMessage.Error("scmConfig.credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage()));
        } else {
            errors.add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage()));
        }
    }
    return errors;
}
Also used : GitException(hudson.plugins.git.GitException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Git(org.jenkinsci.plugins.gitclient.Git) EnvVars(hudson.EnvVars) ServiceException(io.jenkins.blueocean.commons.ServiceException) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) GitClient(org.jenkinsci.plugins.gitclient.GitClient)

Example 5 with Git

use of org.jenkinsci.plugins.gitclient.Git in project blueocean-plugin by jenkinsci.

the class GitUtils method push.

public static void push(String remoteUrl, Repository repo, StandardCredentials credential, String localBranchRef, String remoteBranchRef) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        String pushSpec = "+" + localBranchRef + ":" + remoteBranchRef;
        PushCommand pushCommand = git.push();
        addCredential(repo, pushCommand, credential);
        Iterable<PushResult> resultIterable = pushCommand.setRefSpecs(new RefSpec(pushSpec)).setRemote(remoteUrl).call();
        PushResult result = resultIterable.iterator().next();
        if (result.getRemoteUpdates().isEmpty()) {
            throw new RuntimeException("No remote updates occurred");
        } else {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                if (!RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
                    throw new ServiceException.UnexpectedErrorException("Remote update failed: " + update.getStatus().name() + ": " + update.getMessage());
                }
            }
        }
    } catch (GitAPIException e) {
        if (e.getMessage().toLowerCase().contains("auth")) {
            throw new ServiceException.UnauthorizedException(e.getMessage(), e);
        }
        throw new ServiceException.UnexpectedErrorException("Unable to save and push to: " + remoteUrl + " - " + e.getMessage(), e);
    }
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) PushResult(org.eclipse.jgit.transport.PushResult) PushCommand(org.eclipse.jgit.api.PushCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.jenkinsci.plugins.gitclient.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) ServiceException(io.jenkins.blueocean.commons.ServiceException)

Aggregations

ServiceException (io.jenkins.blueocean.commons.ServiceException)5 Git (org.jenkinsci.plugins.gitclient.Git)5 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)4 RefSpec (org.eclipse.jgit.transport.RefSpec)3 GitException (hudson.plugins.git.GitException)2 IOException (java.io.IOException)2 PushCommand (org.eclipse.jgit.api.PushCommand)2 PushResult (org.eclipse.jgit.transport.PushResult)2 RemoteRefUpdate (org.eclipse.jgit.transport.RemoteRefUpdate)2 JSchException (com.jcraft.jsch.JSchException)1 EnvVars (hudson.EnvVars)1 ErrorMessage (io.jenkins.blueocean.commons.ErrorMessage)1 ArrayList (java.util.ArrayList)1 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)1 FetchCommand (org.eclipse.jgit.api.FetchCommand)1 MergeResult (org.eclipse.jgit.api.MergeResult)1 ConcurrentRefUpdateException (org.eclipse.jgit.api.errors.ConcurrentRefUpdateException)1 JGitInternalException (org.eclipse.jgit.api.errors.JGitInternalException)1 TransportException (org.eclipse.jgit.api.errors.TransportException)1 Ref (org.eclipse.jgit.lib.Ref)1