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:io.fabric8.itests.basic.git.GitUtils.java

License:Apache License

public static void checkoutBranch(Git git, CredentialsProvider credentialsProvider, String remote,
        String branch) throws GitAPIException {
    String current = currentBranch(git);
    if (Objects.equal(current, branch)) {
        return;/*from w  w w.  j  a  v  a  2 s  . c o  m*/
    }
    boolean localExists = localBranchExists(git, branch);
    boolean remoteExists = remoteBranchExists(git, remote, branch);
    if (localExists) {
        git.checkout().setName(branch).call();
    } else if (remoteExists) {
        git.checkout().setName(branch).setCreateBranch(true).setForce(true)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint(remote + "/" + branch).call();
    } else {
        git.branchCreate().setName(branch).setForce(true).call();
        git.checkout().setName(branch).call();
        git.push().setCredentialsProvider(credentialsProvider).setRemote(remote)
                .setRefSpecs(new RefSpec(branch)).setForce(true).call();
    }
    configureBranch(git, remote, getRemote(git, remote), branch);
}

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  w  ww .ja va 2  s.  com
    }

    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:io.fabric8.openshift.agent.DeploymentUpdater.java

License:Apache License

public void updateDeployment(Git git, File baseDir, CredentialsProvider credentials) throws Exception {
    Set<String> bundles = new LinkedHashSet<String>();
    Set<Feature> features = new LinkedHashSet<Feature>();
    Profile overlayProfile = container.getOverlayProfile();
    Profile effectiveProfile = Profiles.getEffectiveProfile(fabricService, overlayProfile);
    bundles.addAll(effectiveProfile.getBundles());
    AgentUtils.addFeatures(features, fabricService, downloadManager, effectiveProfile);

    if (copyFilesIntoGit) {
        copyDeploymentsIntoGit(git, baseDir, bundles, features);
    } else {//w  w w .  ja va  2 s .  co  m
        addDeploymentsIntoPom(git, baseDir, effectiveProfile, bundles, features);
    }

    // now lets do a commit
    String message = "updating deployment";
    git.commit().setMessage(message).call();

    enableDeployDirectory(git, baseDir);

    String branch = GitHelpers.currentBranch(git);
    LOG.info("Pushing deployment changes to branch " + branch + " credentials " + credentials
            + " for container " + container.getId());
    try {
        Iterable<PushResult> results = git.push().setCredentialsProvider(credentials)
                .setRefSpecs(new RefSpec(branch)).setOutputStream(new LoggingOutputStream(LOG)).call();
        /*
                    for (PushResult result : results) {
        LOG.info(result.getMessages());
                    }
        */
        LOG.info("Pushed deployment changes to branch " + branch + " for container " + container.getId());
    } catch (GitAPIException e) {
        LOG.error("Failed to push deployment changes to branch " + branch + " for container "
                + container.getId() + ". Reason: " + e, e);
    }
}

From source file:io.syndesis.git.GitWorkflow.java

License:Apache License

private void commitAndPush(Git git, String authorName, String authorEmail, String message,
        UsernamePasswordCredentialsProvider credentials) throws GitAPIException {

    // git add .//from   www. j a  v  a  2  s  .co  m
    git.add().addFilepattern(".").call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("git add all file");
    }

    // git commit
    RevCommit commit = git.commit().setAuthor(authorName, authorEmail).setMessage(message).call();
    LOG.info("git commit id {}", commit.getId());

    // git push -f, not merging but simply forcing the push (for now)
    Iterable<PushResult> pushResult = git.push().setCredentialsProvider(credentials).setForce(true).call();
    if (!pushResult.iterator().next().getMessages().equals("")) {
        LOG.warn("git push messages: {}", pushResult.iterator().next().getMessages());
    }
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

License:Apache License

private void push(Git git) throws GitAPIException {
    git.push().setRemote(remote).setForce(true).call();
}

From source file:jbyoshi.gitupdate.processor.Push.java

License:Apache License

private static void process(Repository repo, Git git, String remote, Collection<String> branches, Report report)
        throws Exception {
    // Figure out if anything needs to be pushed.
    Map<String, ObjectId> oldIds = new HashMap<>();
    boolean canPush = false;
    for (String branch : branches) {
        BranchConfig config = new BranchConfig(repo.getConfig(), branch);
        ObjectId target = repo.getRef(branch).getObjectId();

        Ref remoteRef = repo.getRef(config.getRemoteTrackingBranch());
        if (remoteRef == null || !target.equals(remoteRef.getObjectId())) {
            canPush = true;/*from   w  w w .j  av  a 2 s  .c om*/
        }
        oldIds.put(branch, remoteRef == null ? ObjectId.zeroId() : remoteRef.getObjectId());
    }

    if (!canPush) {
        return;
    }

    PushCommand push = git.push().setCredentialsProvider(Prompts.INSTANCE).setTimeout(5).setRemote(remote);
    for (String branch : branches) {
        push.add(Constants.R_HEADS + branch);
    }
    for (PushResult result : push.call()) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            if (update.getStatus() == RemoteRefUpdate.Status.OK) {
                String branchName = Utils.getShortBranch(update.getSrcRef());
                ObjectId oldId = oldIds.get(branchName);
                String old = oldId.equals(ObjectId.zeroId()) ? "new branch" : oldId.name();
                report.newChild(branchName + ": " + old + " -> " + update.getNewObjectId().name()).modified();
            }
        }
    }
}

From source file:licenseUtil.Utils.java

License:Apache License

public static void commitAndPushRepository(String gitDir, String message) {
    try {/* w  w  w  .ja  v  a 2s  .c  om*/
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);

        logger.info("commit & push to repo (" + gitDir + "): " + message);
        git.commit().setMessage(message).call();
        git.push().call();
    } catch (GitAPIException e) {
        logger.warn("Could not commit and push local repository: \"" + gitDir + "\" with message: \"" + message
                + "\" because of " + e.getMessage());
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}

From source file:models.PullRequestTest.java

License:Apache License

@Before
public void initRepositories() throws Exception {
    GitRepository.setRepoPrefix(REPO_PREFIX);

    app = support.Helpers.makeTestApplication();
    Helpers.start(app);/*ww  w .java  2  s .c o m*/

    Project project = Project.findByOwnerAndProjectName("yobi", "projectYobi");
    forkedProject = Project.findByOwnerAndProjectName("yobi", "projectYobi-1");

    // 1. projectYobi  
    RepositoryService.createRepository(project);

    // 2. projectYobi ?  
    {
        String localRepoPath = LOCAL_REPO_PREFIX + project.name;
        Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(project))
                .setDirectory(new File(localRepoPath)).call();
        Repository repo = git.getRepository();
        baseCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncat\n", "commit 1");
        git.push().setRefSpecs(new RefSpec("+refs/heads/master:refs/heads/master")).call();
    }

    // 3. ??? ? ??  
    GitRepository.cloneLocalRepository(project, forkedProject);

    // 4. ??? ?     ? ? ? 
    {
        String localRepoPath = LOCAL_REPO_PREFIX + forkedProject.name;
        Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(forkedProject))
                .setDirectory(new File(localRepoPath)).call();
        git.branchCreate().setName("fix/1").call();
        git.checkout().setName("fix/1").call();
        Repository repo = git.getRepository();
        assertThat(repo.isBare()).describedAs("projectYobi-1 must be non-bare").isFalse();
        firstCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncorn\n", "commit 1");
        secondCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncake\n", "commit 2");
        git.push().setRefSpecs(new RefSpec("+refs/heads/fix/1:refs/heads/fix/1")).call();
    }

    // 5.   projectYobi? pullrequest .
    pullRequest = PullRequest.createNewPullRequest(forkedProject, project, "refs/heads/fix/1",
            "refs/heads/master");
    pullRequest.save();

    // 6. attempt merge
    boolean isConflict = pullRequest.updateMerge().conflicts();

    assertThat(isConflict).isFalse();
}

From source file:org.apache.gobblin.service.modules.flow.MultiHopFlowCompilerTest.java

License:Apache License

@Test(dependsOnMethods = "testMulticastPath")
public void testGitFlowGraphMonitorService()
        throws IOException, GitAPIException, URISyntaxException, InterruptedException {
    File remoteDir = new File(TESTDIR + "/remote");
    File cloneDir = new File(TESTDIR + "/clone");
    File flowGraphDir = new File(cloneDir, "/gobblin-flowgraph");

    //Clean up/*from   w w w  .j a v a  2  s .c o  m*/
    cleanUpDir(TESTDIR);

    // Create a bare repository
    RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED);
    Repository remoteRepo = fileKey.open(false);
    remoteRepo.create(true);

    Git gitForPush = Git.cloneRepository().setURI(remoteRepo.getDirectory().getAbsolutePath())
            .setDirectory(cloneDir).call();

    // push an empty commit as a base for detecting changes
    gitForPush.commit().setMessage("First commit").call();
    RefSpec masterRefSpec = new RefSpec("master");
    gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();

    URI flowTemplateCatalogUri = this.getClass().getClassLoader().getResource("template_catalog").toURI();

    Config config = ConfigBuilder.create()
            .addPrimitive(
                    GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                            + ConfigurationKeys.GIT_MONITOR_REPO_URI,
                    remoteRepo.getDirectory().getAbsolutePath())
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TESTDIR + "/git-flowgraph")
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5)
            .addPrimitive(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY,
                    flowTemplateCatalogUri.toString())
            .build();

    //Create a MultiHopFlowCompiler instance
    specCompiler = new MultiHopFlowCompiler(config, Optional.absent(), false);

    specCompiler.setActive(true);

    //Ensure node1 is not present in the graph
    Assert.assertNull(specCompiler.getFlowGraph().getNode("node1"));

    // push a new node file
    File nodeDir = new File(flowGraphDir, "node1");
    File nodeFile = new File(nodeDir, "node1.properties");
    nodeDir.mkdirs();
    nodeFile.createNewFile();
    Files.write(FlowGraphConfigurationKeys.DATA_NODE_IS_ACTIVE_KEY + "=true\nparam1=val1" + "\n", nodeFile,
            Charsets.UTF_8);

    // add, commit, push node
    gitForPush.add().addFilepattern(formNodeFilePath(flowGraphDir, nodeDir.getName(), nodeFile.getName()))
            .call();
    gitForPush.commit().setMessage("Node commit").call();
    gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();

    // polling is every 5 seconds, so wait twice as long and check
    TimeUnit.SECONDS.sleep(10);

    //Test that a DataNode is added to FlowGraph
    DataNode dataNode = specCompiler.getFlowGraph().getNode("node1");
    Assert.assertEquals(dataNode.getId(), "node1");
    Assert.assertEquals(dataNode.getRawConfig().getString("param1"), "val1");
}

From source file:org.apache.maven.scm.provider.git.jgit.command.JGitUtils.java

License:Apache License

public static Iterable<PushResult> push(ScmLogger logger, Git git, GitScmProviderRepository repo,
        RefSpec refSpec) throws GitAPIException, InvalidRemoteException, TransportException {
    CredentialsProvider credentials = JGitUtils.prepareSession(logger, git, repo);
    Iterable<PushResult> pushResultList = git.push().setCredentialsProvider(credentials).setRefSpecs(refSpec)
            .call();/*from w  w w. ja v  a  2 s  . c  om*/
    for (PushResult pushResult : pushResultList) {
        Collection<RemoteRefUpdate> ru = pushResult.getRemoteUpdates();
        for (RemoteRefUpdate remoteRefUpdate : ru) {
            logger.info(remoteRefUpdate.getStatus() + " - " + remoteRefUpdate.toString());
        }
    }
    return pushResultList;
}