Example usage for org.eclipse.jgit.api Git push

List of usage examples for org.eclipse.jgit.api Git push

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git push.

Prototype

public PushCommand push() 

Source Link

Document

Return a command object to execute a Push command

Usage

From source file:ch.sbb.releasetrain.git.GitRepoImpl.java

License:Apache License

@Override
public void addCommitPush() {
    try {/*w  w  w .  ja va  2s.  co  m*/
        Git git = gitOpen();

        git.add().addFilepattern(".").call();

        // status
        Status status = git.status().call();

        // rm the deleted ones
        if (status.getMissing().size() > 0) {
            for (String rm : status.getMissing()) {
                git.rm().addFilepattern(rm).call();
            }
        }

        // commit and push if needed
        if (!status.hasUncommittedChanges()) {
            log.debug("not commiting git, because there are no changes");
            return;
        }

        git.commit().setMessage("Automatic commit by releasetrain").call();
        git.push().setCredentialsProvider(credentialsProvider()).call();
    } catch (Exception e) {
        throw new GitException(e.getMessage(), e);
    }
}

From source file:ch.sbb.releasetrain.git.GitRepoImpl.java

License:Apache License

/**
 * Use with care!//from  www .  j  a  v a2s. co  m
 */
public boolean deleteBranch() {
    if (!branch.startsWith("feature/")) {
        throw new GitException("Can only delete feature branch.");
    }
    try {

        final Git git = gitOpen();
        git.checkout().setCreateBranch(true).setName("feature/temp_" + UUID.randomUUID()).call();
        List<String> deletedBranches = git.branchDelete().setBranchNames(branch).setForce(true).call();
        if (deletedBranches.size() == 1) {
            // delete branch 'branchToDelete' on remote 'origin'
            RefSpec refSpec = new RefSpec().setSource(null).setDestination("refs/heads/" + branch);
            Iterable<PushResult> results = git.push().setCredentialsProvider(credentialsProvider())
                    .setRefSpecs(refSpec).setRemote("origin").call();
            for (PushResult result : results) {
                RemoteRefUpdate myUpdate = result.getRemoteUpdate("refs/heads/" + branch);
                if (myUpdate.isDelete() && myUpdate.getStatus() == RemoteRefUpdate.Status.OK) {
                    return true;
                }
            }
        }
        return false;
    } catch (IOException | GitAPIException e) {
        throw new GitException("Delete branch failed", e);
    }
}

From source file:com.athomas.androidkickstartr.util.GitHubber.java

License:Apache License

public Repository createCommit(File srcFolder, String applicationName) throws IOException, GitAPIException {
    Repository repository = repositoryService.createRepository(new Repository().setName(applicationName));

    String cloneUrl = repository.getCloneUrl();

    InitCommand init = new InitCommand();
    init.setDirectory(srcFolder);// w ww. j a v a 2  s .  c  o  m
    init.setBare(false);
    Git git = init.call();

    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", cloneUrl);
    config.save();

    UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(accessToken, "");
    git.add().addFilepattern(".").call();
    git.commit().setMessage(COMMIT_MESSAGE).call();
    git.push().setCredentialsProvider(user).call();

    return repository;
}

From source file:com.barchart.jenkins.cascade.PluginScmGit.java

License:BSD License

/**
 * See {@link Git#push()}//from   w  w  w.  java2  s.co  m
 */
public static Iterable<PushResult> doPush(final File workspace, final String remote, final RefSpec spec) {
    try {
        final Git git = Git.open(workspace);
        return git.push().setRemote(remote).setRefSpecs(spec).call();
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cloudcontrolled.cctrl.maven.plugin.push.CloudcontrolledPush.java

License:Apache License

private String push(String remoteLocation) throws MojoExecutionException {
    Repository repository = null;//www.  jav  a 2  s . co  m
    Git git;
    try {
        repository = getRepository();
        git = Git.wrap(repository);

        PushCommand pushCommand = git.push();
        pushCommand.setRemote(remoteLocation);
        pushCommand.setRefSpecs(new RefSpec(repository.getFullBranch()));

        Iterable<PushResult> pushResult = pushCommand.call();
        Iterator<PushResult> result = pushResult.iterator();

        StringBuffer buffer = new StringBuffer();
        if (result.hasNext()) {
            while (result.hasNext()) {
                String line = result.next().getMessages();
                if (!line.isEmpty()) {
                    buffer.append(line);
                    if (result.hasNext()) {
                        buffer.append(System.getProperty("line.separator"));
                    }
                }
            }
        }

        return buffer.toString();
    } catch (Exception e) {
        throw new MojoExecutionException(e.getClass().getSimpleName(), e);
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testAnonymousPush() throws Exception {
    GitBlitSuite.close(ticgitFolder);//from ww  w . j  a  v  a  2  s.co  m
    if (ticgitFolder.exists()) {
        FileUtils.delete(ticgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    RepositoryModel model = repositories().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.NONE;
    repositories().updateRepositoryModel(model.name, model, false);

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(ticgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    GitBlitSuite.close(clone.call());
    assertTrue(true);

    Git git = Git.open(ticgitFolder);
    File file = new File(ticgitFolder, "TODO");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// hellol " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();
    Iterable<PushResult> results = git.push().setPushAll().call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
        }
    }
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testSubfolderPush() throws Exception {
    GitBlitSuite.close(jgitFolder);//from w  w  w.  ja v a  2s  .  co  m
    if (jgitFolder.exists()) {
        FileUtils.delete(jgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/test/jgit.git", url));
    clone.setDirectory(jgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    GitBlitSuite.close(clone.call());
    assertTrue(true);

    Git git = Git.open(jgitFolder);
    File file = new File(jgitFolder, "TODO");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();
    Iterable<PushResult> results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
        }
    }
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testPushToFrozenRepo() throws Exception {
    GitBlitSuite.close(jgitFolder);/*from   ww  w  .  j a va  2 s.c om*/
    if (jgitFolder.exists()) {
        FileUtils.delete(jgitFolder, FileUtils.RECURSIVE | FileUtils.RETRY);
    }

    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/test/jgit.git", url));
    clone.setDirectory(jgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    GitBlitSuite.close(clone.call());
    assertTrue(true);

    // freeze repo
    RepositoryModel model = repositories().getRepositoryModel("test/jgit.git");
    model.isFrozen = true;
    repositories().updateRepositoryModel(model.name, model, false);

    Git git = Git.open(jgitFolder);
    File file = new File(jgitFolder, "TODO");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();

    Iterable<PushResult> results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.REJECTED_OTHER_REASON, update.getStatus());
        }
    }

    // unfreeze repo
    model.isFrozen = false;
    repositories().updateRepositoryModel(model.name, model, false);

    results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.OK, update.getStatus());
        }
    }
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

@Test
public void testPushToNonBareRepository() throws Exception {
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/working/jgit", url));
    clone.setDirectory(jgit2Folder);// w w w.java  2  s  .  c  o m
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    GitBlitSuite.close(clone.call());
    assertTrue(true);

    Git git = Git.open(jgit2Folder);
    File file = new File(jgit2Folder, "NONBARE");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit followed by push to non-bare repository").call();
    Iterable<PushResult> results = git.push().setPushAll()
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)).call();
    GitBlitSuite.close(git);
    for (PushResult result : results) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            assertEquals(Status.REJECTED_OTHER_REASON, update.getStatus());
        }
    }
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

private void testCommitterVerification(UserModel user, String displayName, String emailAddress,
        boolean expectedSuccess) throws Exception {

    delete(user);/*  w ww .j  av  a 2  s .c  o  m*/

    CredentialsProvider cp = new UsernamePasswordCredentialsProvider(user.username, user.password);

    // fork from original to a temporary bare repo
    File verification = new File(GitBlitSuite.REPOSITORIES, "refchecks/verify-committer.git");
    if (verification.exists()) {
        FileUtils.delete(verification, FileUtils.RECURSIVE);
    }
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(verification);
    clone.setBare(true);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    // require push permissions and committer verification
    RepositoryModel model = repositories().getRepositoryModel("refchecks/verify-committer.git");
    model.authorizationControl = AuthorizationControl.NAMED;
    model.accessRestriction = AccessRestrictionType.PUSH;
    model.verifyCommitter = true;

    // grant user push permission
    user.setRepositoryPermission(model.name, AccessPermission.PUSH);

    gitblit().addUser(user);
    repositories().updateRepositoryModel(model.name, model, false);

    // clone temp bare repo to working copy
    File local = new File(GitBlitSuite.REPOSITORIES, "refchecks/verify-wc");
    if (local.exists()) {
        FileUtils.delete(local, FileUtils.RECURSIVE);
    }
    clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/{1}", url, model.name));
    clone.setDirectory(local);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    Git git = Git.open(local);

    // force an identity which may or may not match the account's identity
    git.getRepository().getConfig().setString("user", null, "name", displayName);
    git.getRepository().getConfig().setString("user", null, "email", emailAddress);
    git.getRepository().getConfig().save();

    // commit a file and push it
    File file = new File(local, "PUSHCHK");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("push test").call();
    Iterable<PushResult> results = git.push().setCredentialsProvider(cp).setRemote("origin").call();

    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (expectedSuccess) {
            assertTrue("Verification failed! User was NOT able to push commit! " + status.name(),
                    Status.OK.equals(status));
        } else {
            assertTrue("Verification failed! User was able to push commit! " + status.name(),
                    Status.REJECTED_OTHER_REASON.equals(status));
        }
    }

    GitBlitSuite.close(git);
    // close serving repository
    GitBlitSuite.close(verification);
}