Example usage for org.eclipse.jgit.api PushCommand setRemote

List of usage examples for org.eclipse.jgit.api PushCommand setRemote

Introduction

In this page you can find the example usage for org.eclipse.jgit.api PushCommand setRemote.

Prototype

public PushCommand setRemote(String remote) 

Source Link

Document

The remote (uri or name) used for the push operation.

Usage

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public void push(final LocalRepoBean repoBean, final String remoteName) throws GitException {
    try {//  w w  w.  ja  v  a  2s.c  o  m
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getRepoDirectory().toFile()).findGitDir().build();
        Git git = new org.eclipse.jgit.api.Git(repository);

        // dry run the push - if the push cannot be done automatically we have no way to recover so we just log
        // and throw an exception
        PushCommand dryRunPushCommand = git.push();
        dryRunPushCommand.setRemote(remoteName);
        dryRunPushCommand.setDryRun(true);
        Iterable<PushResult> dryRunResult = dryRunPushCommand.call();
        for (PushResult result : dryRunResult) {
            for (RemoteRefUpdate remoteRefUpdate : result.getRemoteUpdates()) {
                switch (remoteRefUpdate.getStatus()) {
                case OK:
                case UP_TO_DATE:
                    continue;
                default:
                    throw new GitException("During a dry run of a push one of the updates would have failed "
                            + "so the push was aborted for repo " + repoBean + " to remote "
                            + dryRunPushCommand.getRemote());
                }
            }
        }

        // if we get to this point the dry run was OK so try the real thing
        PushCommand realPushCommand = git.push();
        realPushCommand.setRemote(remoteName);
        Iterable<PushResult> pushResults = realPushCommand.call();
        for (PushResult result : pushResults) {
            for (RemoteRefUpdate remoteRefUpdate : result.getRemoteUpdates()) {
                switch (remoteRefUpdate.getStatus()) {
                case OK:
                case UP_TO_DATE:
                    continue;
                default:
                    throw new GitException(
                            "Push failed for " + repoBean + " to remote " + dryRunPushCommand.getRemote());
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
}

From source file:io.fabric8.collector.git.GitHelpers.java

License:Apache License

public static RevCommit doCommitAndPush(Git git, String message, UserDetails userDetails, PersonIdent author,
        String branch, String origin, boolean pushOnCommit) throws GitAPIException {
    CommitCommand commit = git.commit().setAll(true).setMessage(message);
    if (author != null) {
        commit = commit.setAuthor(author);
    }/*from  w  w w .ja va 2  s. com*/

    RevCommit answer = commit.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage());
    }

    if (pushOnCommit) {
        PushCommand push = git.push();
        configureCommand(push, userDetails);
        Iterable<PushResult> results = push.setRemote(origin).call();
        for (PushResult result : results) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch
                        + " updates: " + toString(result.getRemoteUpdates()));
            }
        }
    }
    return answer;
}

From source file:io.fabric8.forge.rest.client.ForgeTestSupport.java

License:Apache License

protected Build assertCodeChangeTriggersWorkingBuild(JenkinsServer jenkins, String jenkinsUrl,
        final String projectName, Build firstBuild, String folderName) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {//from w  ww  .  ja v a  2  s  .  c o  m
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }

    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent())
            .setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;

    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JenkinsServer jenkins = createJenkinsServer(forgeClient.getKubernetesClient(), jenkinsNamespace);
            JobWithDetails job = assertJob(jenkins, folderName, projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber())
                    .describedAs("Waiting for latest build for job " + projectName + " to start")
                    .isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(jenkins, jenkinsUrl, folderName, projectName);
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected Iterable<PushResult> doPush(Git git) throws Exception {
    PushCommand command = git.push();
    configureCommand(command, userDetails);
    return command.setRemote(getRemote()).call();
}

From source file:io.fabric8.maven.HelmPushMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (!isRootReactorBuild()) {
        getLog().info("Not the root reactor build so not committing changes");
        return;//from   ww w  .j ava  2  s.c  o  m
    }

    File outputDir = getHelmRepoFolder();
    if (!Files.isDirectory(outputDir)) {
        throw new MojoExecutionException(
                "No helm repository exists for " + outputDir + ". Did you run `mvn fabric8:helm` yet?");
    }
    File gitFolder = new File(outputDir, ".git");
    if (!Files.isDirectory(gitFolder)) {
        throw new MojoExecutionException(
                "No helm git repository exists for " + gitFolder + ". Did you run `mvn fabric8:helm` yet?");
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Git git = null;

    try {
        Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        git = new Git(repository);

        git.add().addFilepattern(".").call();
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to add files to the helm git repository: " + e, e);
    }
    CommitCommand commit = git.commit().setAll(true).setMessage(commitMessage);
    PersonIdent author = null;
    if (Strings.isNotBlank(userName) && Strings.isNotBlank(emailAddress)) {
        author = new PersonIdent(userName, emailAddress);
    }
    if (author != null) {
        commit = commit.setAuthor(author);
    }

    try {
        RevCommit answer = commit.call();
        getLog().info("Committed " + answer.getId() + " " + answer.getFullMessage());
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to commit changes to help repository: " + e, e);
    }

    if (pushChanges) {
        PushCommand push = git.push();
        try {
            push.setRemote(remoteRepoName).call();

            getLog().info("Pushed commits upstream to " + getHelmGitUrl());
        } catch (GitAPIException e) {
            throw new MojoExecutionException(
                    "Failed to push helm git changes to remote repository " + remoteRepoName + ": " + e, e);
        }
    }

}

From source file:org.ajoberstar.gradle.git.tasks.GitPush.java

License:Apache License

/**
 * Pushes changes to a remote repository.
 *///from w  ww.ja  v  a 2s  .  c o m
@TaskAction
public void push() {
    PushCommand cmd = getGit().push();
    TransportAuthUtil.configure(cmd, this);
    cmd.setRemote(getRemote());
    if (isPushTags()) {
        cmd.setPushTags();
    }
    if (isPushAll()) {
        cmd.setPushAll();
    }
    cmd.setForce(isForce());
    try {
        cmd.call();
    } catch (Exception e) {
        throw new GradleException("Problem pushing to repository.", e);
    }
    //TODO add progress monitor to go to Gradle status bar
}

From source file:org.codehaus.mojo.versions.BumpMojo.java

License:Apache License

void gitPush(String o, String d) throws MojoExecutionException {
    try {//from   w w  w.ja v  a 2  s .  com
        RefSpec spec = new RefSpec(d + ":" + d);
        PushCommand ff = git.push();
        ff.setRemote(o);
        ff.setRefSpecs(spec);
        ff.setPushTags();
        Iterable<PushResult> f = ff.call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public PushResponse push(PushRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
            ConfigConstants.CONFIG_KEY_URL);
    PushResponse pushResponseDto = newDto(PushResponse.class);
    try {//from w w w . jav a 2 s.c o  m
        PushCommand pushCommand = getGit().push();

        if (request.getRemote() != null) {
            pushCommand.setRemote(remoteName);
        }
        List<String> refSpec = request.getRefSpec();
        if (!refSpec.isEmpty()) {
            List<RefSpec> refSpecInst = new ArrayList<>(refSpec.size());
            refSpecInst.addAll(refSpec.stream().map(RefSpec::new).collect(Collectors.toList()));
            pushCommand.setRefSpecs(refSpecInst);
        }

        pushCommand.setForce(request.isForce());

        int timeout = request.getTimeout();
        if (timeout > 0) {
            pushCommand.setTimeout(timeout);
        }

        @SuppressWarnings("unchecked")
        Iterable<PushResult> pushResults = (Iterable<PushResult>) executeRemoteCommand(remoteUri, pushCommand);
        PushResult pushResult = pushResults.iterator().next();
        return addCommandOutputUpdates(pushResponseDto, request, pushResult);
    } catch (GitAPIException exception) {
        if ("origin: not found.".equals(exception.getMessage())) {
            throw new GitException(ERROR_NO_REMOTE_REPOSITORY, exception);
        } else {
            throw new GitException(exception.getMessage(), exception);
        }
    }
}

From source file:org.eclipse.orion.server.git.jobs.PushJob.java

License:Open Source License

private IStatus doPush() throws IOException, CoreException, URISyntaxException, GitAPIException {
    // /git/remote/{remote}/{branch}/file/{path}
    File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
    Repository db = new FileRepository(gitDir);
    Git git = new Git(db);

    PushCommand pushCommand = git.push();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));
    pushCommand.setCredentialsProvider(credentials);

    RefSpec spec = new RefSpec(srcRef + ':' + Constants.R_HEADS + branch);
    pushCommand.setRemote(remote).setRefSpecs(spec);
    if (tags)//from  w w  w.j  av  a  2 s.  com
        pushCommand.setPushTags();
    pushCommand.setForce(force);
    Iterable<PushResult> resultIterable = pushCommand.call();
    PushResult pushResult = resultIterable.iterator().next();
    // this set will contain only OK status or UP_TO_DATE status
    Set<RemoteRefUpdate.Status> statusSet = new HashSet<RemoteRefUpdate.Status>();
    for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
        final String rm = rru.getRemoteName();
        // check status only for branch given in the URL or tags
        if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS)) {
            RemoteRefUpdate.Status status = rru.getStatus();
            // any status different from UP_TO_DATE and OK should generate warning
            if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
                return new Status(IStatus.WARNING, GitActivator.PI_GIT, status.name(),
                        new Throwable(rru.getMessage()));
            // add OK or UP_TO_DATE status to the set
            statusSet.add(status);
        }
        // TODO: return results for all updated branches once push is available for remote, see bug 352202
    }
    if (statusSet.contains(RemoteRefUpdate.Status.OK))
        // if there is OK status in the set -> something was updated
        return Status.OK_STATUS;
    else
        // if there is no OK status in the set -> only UP_TO_DATE status is possible
        return new Status(IStatus.WARNING, GitActivator.PI_GIT, RemoteRefUpdate.Status.UP_TO_DATE.name());
}

From source file:org.eclipse.orion.server.git.servlets.PushJob.java

License:Open Source License

private IStatus doPush() throws IOException, CoreException, JGitInternalException, InvalidRemoteException,
        URISyntaxException, JSONException {
    // /git/remote/{remote}/{branch}/file/{path}
    File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
    Repository db = new FileRepository(gitDir);
    Git git = new Git(db);

    PushCommand pushCommand = git.push();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), path.segment(0));
    credentials.setUri(remoteConfig.getURIs().get(0));
    pushCommand.setCredentialsProvider(credentials);

    // ObjectId ref = db.resolve(srcRef);
    RefSpec spec = new RefSpec(srcRef + ":" + Constants.R_HEADS + path.segment(1)); //$NON-NLS-1$
    pushCommand.setRemote(path.segment(0)).setRefSpecs(spec);
    if (tags)/*from  ww  w .ja v  a 2  s  .  c  o  m*/
        pushCommand.setPushTags();
    pushCommand.setForce(force);
    Iterable<PushResult> resultIterable = pushCommand.call();
    PushResult pushResult = resultIterable.iterator().next();
    // this set will contain only OK status or UP_TO_DATE status
    Set<RemoteRefUpdate.Status> statusSet = new HashSet<RemoteRefUpdate.Status>();
    for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
        final String rm = rru.getRemoteName();
        // final String sr = rru.isDelete() ? null : rru.getSrcRef();
        // check status only for branch given in the URL or tags
        if (path.segment(1).equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS)) {
            RemoteRefUpdate.Status status = rru.getStatus();
            // any status different from UP_TO_DATE and OK should generate warning
            if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
                return new Status(IStatus.WARNING, GitActivator.PI_GIT, status.name());
            // add OK or UP_TO_DATE status to the set
            statusSet.add(status);
        }
        // TODO: return results for all updated branches once push is available for remote, see bug 342727, comment 1
    }
    if (statusSet.contains(RemoteRefUpdate.Status.OK))
        // if there is OK status in the set -> something was updated
        return Status.OK_STATUS;
    else
        // if there is no OK status in the set -> only UP_TO_DATE status is possible
        return new Status(IStatus.WARNING, GitActivator.PI_GIT, RemoteRefUpdate.Status.UP_TO_DATE.name());
}