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

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

Introduction

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

Prototype

public PullCommand pull() 

Source Link

Document

Return a command object to execute a Pull command

Usage

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;
    try {//ww  w  . j  a va 2 s  .c o m
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:org.eclipse.oomph.gitbash.repository.PushDirectAction.java

License:Open Source License

@Override
protected void run(Shell shell, final Repository repository) throws Exception {
    new Job("Pushing directly") {
        @Override/* www  . j a v a2  s  .co  m*/
        protected IStatus run(IProgressMonitor monitor) {
            monitor.beginTask(getName(), 101);

            try {
                Git git = Git.wrap(repository);
                monitor.worked(1);

                git.push().setRemote("direct").setProgressMonitor(
                        new EclipseGitProgressTransformer(new SubProgressMonitor(monitor, 50))).call();

                monitor.setTaskName("Pulling");
                git.pull().setProgressMonitor(
                        new EclipseGitProgressTransformer(new SubProgressMonitor(monitor, 50))).call();

                return Status.OK_STATUS;
            } catch (Exception ex) {
                return Activator.getStatus(ex);
            } finally {
                monitor.done();
            }
        }
    }.schedule();
}

From source file:org.eclipse.orion.server.filesystem.git.GitFileStore.java

License:Open Source License

/**
 * pulls from the remote/*from   ww  w . ja va  2  s.co m*/
 * @throws CoreException
 */
private void pull() throws CoreException {
    Transport transport = null;
    try {
        Repository repo = getLocalRepo();
        Git git = new Git(repo);
        PullCommand pull = git.pull();
        pull.setCredentialsProvider(getCredentialsProvider());
        PullResult pullResult = pull.call();
        LogHelper.log(new Status(IStatus.INFO, Activator.PI_GIT, 1,
                "Pull (fetch/merge) result " + pullResult.getFetchResult().getMessages() + "/"
                        + pullResult.getMergeResult().getMergeStatus() + " for " + this,
                null));
    } catch (Exception e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PI_GIT, IStatus.ERROR, e.getMessage(), e));
    } finally {
        if (transport != null)
            transport.close();
    }
}

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

License:Open Source License

private IStatus doPull() throws IOException, GitAPIException, CoreException {
    Repository db = new FileRepository(GitUtils.getGitDir(path));

    Git git = new Git(db);
    PullCommand pc = git.pull();
    pc.setCredentialsProvider(credentials);
    pc.setTransportConfigCallback(new TransportConfigCallback() {
        @Override/*from   w ww  .  ja  v  a  2  s .c  o  m*/
        public void configure(Transport t) {
            credentials.setUri(t.getURI());
        }
    });
    PullResult pullResult = pc.call();

    // handle result
    if (pullResult.isSuccessful()) {
        return Status.OK_STATUS;
    } else {

        FetchResult fetchResult = pullResult.getFetchResult();

        IStatus fetchStatus = FetchJob.handleFetchResult(fetchResult);
        if (!fetchStatus.isOK()) {
            return fetchStatus;
        }

        MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();
        if (mergeStatus.isSuccessful()) {
            return Status.OK_STATUS;
        } else {
            return new Status(IStatus.ERROR, GitActivator.PI_GIT, mergeStatus.name());
        }
    }
}

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

License:Open Source License

@Test
public void testCreateTrackingBranch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject projectTop = createProjectOrLink(workspaceLocation, getMethodName() + "-top", null);
    IPath clonePathTop = new Path("file").append(projectTop.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    JSONObject projectFolder = createProjectOrLink(workspaceLocation, getMethodName() + "-folder", null);
    IPath clonePathFolder = new Path("file").append(projectFolder.getString(ProtocolConstants.KEY_ID))
            .append("folder").makeAbsolute();

    IPath[] clonePaths = new IPath[] { clonePathTop, clonePathFolder };

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

        // get project/folder metadata
        WebRequest request = getGetFilesRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());

        String projectLocation = project.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
        String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE);

        // create local branch tracking origin/master
        final String BRANCH_NAME = "a";
        final String REMOTE_BRANCH = Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER;

        branch(branchesLocation, BRANCH_NAME, REMOTE_BRANCH);

        // modify
        request = getPutFileRequest(projectLocation + "test.txt", "some change");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // add/*from   w w w . ja v a 2 s  .c  om*/
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // push
        ServerStatus pushStatus = push(gitRemoteUri, 1, 0, Constants.MASTER, Constants.HEAD, false);
        assertEquals(true, pushStatus.isOK());

        // TODO: replace with RESTful API for git pull when available
        // try to pull - up to date status is expected
        Git git = new Git(getRepositoryForContentLocation(cloneContentLocation));
        PullResult pullResults = git.pull().call();
        assertEquals(Constants.DEFAULT_REMOTE_NAME, pullResults.getFetchedFrom());
        assertEquals(MergeStatus.ALREADY_UP_TO_DATE, pullResults.getMergeResult().getMergeStatus());
        assertNull(pullResults.getRebaseResult());

        // checkout branch which was created a moment ago
        response = checkoutBranch(cloneLocation, BRANCH_NAME);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // TODO: replace with RESTful API for git pull when available
        // try to pull again - now fast forward update is expected
        pullResults = git.pull().call();
        assertEquals(Constants.DEFAULT_REMOTE_NAME, pullResults.getFetchedFrom());
        assertEquals(MergeStatus.FAST_FORWARD, pullResults.getMergeResult().getMergeStatus());
        assertNull(pullResults.getRebaseResult());
    }
}

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

License:Open Source License

@Test
public void testGetCloneAndPull() throws Exception {
    // see bug 339254
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = getWorkspaceId(workspaceLocation);

    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get clones for workspace
    WebRequest request = listGitClonesRequest(workspaceId, null);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject clones = new JSONObject(response.getText());
    JSONArray clonesArray = clones.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, clonesArray.length());

    Git git = new Git(getRepositoryForContentLocation(contentLocation));
    // TODO: replace with RESTful API when ready, see bug 339114
    PullResult pullResult = git.pull().call();
    assertEquals(pullResult.getMergeResult().getMergeStatus(), MergeStatus.ALREADY_UP_TO_DATE);
    assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState());
}

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

License:Open Source License

@Test
public void testConflict() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    // clone1: create
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    String projectId1 = project1.getString(ProtocolConstants.KEY_ID);
    IPath clonePath1 = new Path("file").append(project1.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    String contentLocation1 = clone(clonePath1).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get project metadata
    WebRequest request = getGetFilesRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT);
    String gitIndexUri1 = gitSection1.getString(GitConstants.KEY_INDEX);
    String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD);
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);

    // clone2: create
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    String projectId2 = project2.getString(ProtocolConstants.KEY_ID);
    IPath clonePath2 = new Path("file").append(project2.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    String contentLocation2 = clone(clonePath2).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get project metadata
    request = getGetFilesRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
    String gitIndexUri2 = gitSection2.getString(GitConstants.KEY_INDEX);
    String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD);
    String gitStatusUri2 = gitSection2.getString(GitConstants.KEY_STATUS);

    // clone1: change
    request = getPutFileRequest(projectId1 + "/test.txt", "change from clone1");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri1);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "change from clone1", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: push
    ServerStatus pushStatus = push(gitRemoteUri1, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(true, pushStatus.isOK());

    // this is how EGit checks for conflicts
    Repository db1 = getRepositoryForContentLocation(contentLocation1);
    Git git = new Git(db1);
    DirCache cache = db1.readDirCache();
    DirCacheEntry entry = cache.getEntry("test.txt");
    assertTrue(entry.getStage() == 0);/*ww  w. j a va 2  s  .c om*/

    // clone2: change
    request = getPutFileRequest(projectId2 + "/test.txt", "change from clone2");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri2, "change from clone2", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: pull
    // TODO: replace with REST API for git pull once bug 339114 is fixed
    Repository db2 = getRepositoryForContentLocation(contentLocation2);
    git = new Git(db2);
    PullResult pullResult = git.pull().call();
    assertEquals(pullResult.getMergeResult().getMergeStatus(), MergeStatus.CONFLICTING);

    // this is how EGit checks for conflicts
    cache = db2.readDirCache();
    entry = cache.getEntry("test.txt");
    assertTrue(entry.getStage() > 0);

    request = getGetGitStatusRequest(gitStatusUri2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject statusResponse = new JSONObject(response.getText());
    JSONArray statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_ADDED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_CHANGED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_MISSING);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_MODIFIED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_REMOVED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_UNTRACKED);
    assertEquals(0, statusArray.length());
    statusArray = statusResponse.getJSONArray(GitConstants.KEY_STATUS_CONFLICTING);
    assertEquals(1, statusArray.length());
    assertNotNull(getChildByName(statusArray, "test.txt"));
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private void pullSnippets(Git git, String checkoutBranch)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException, CoreException {
    CheckoutCommand checkout = git.checkout();
    checkout.setName(checkoutBranch);/* w  w  w.jav  a2s. co  m*/
    checkout.setStartPoint("origin/" + checkoutBranch);
    checkout.setCreateBranch(!branchExistsLocally(git, "refs/heads/" + checkoutBranch));
    checkout.call();

    PullCommand pull = git.pull();
    pull.call();
}

From source file:org.exist.git.xquery.Pull.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//ww  w .j a  v a  2s  .  co  m
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        Git git = Git.open(new Resource(localPath), FS);

        PullResult answer = git.pull().setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(args[1].getStringValue(), args[2].getStringValue()))
                .call();

        MemTreeBuilder builder = getContext().getDocumentBuilder();

        int nodeNr = builder.startElement(PULL, null);
        builder.addAttribute(IS_SUCCESSFUL, Boolean.toString(answer.isSuccessful()));

        MergeResult merge = answer.getMergeResult();

        if (merge != null) {
            builder.startElement(MERGE, null);
            builder.addAttribute(STATUS, merge.getMergeStatus().toString());
            builder.addAttribute(IS_SUCCESSFUL, Boolean.toString(merge.getMergeStatus().isSuccessful()));

            for (ObjectId commit : merge.getMergedCommits()) {
                builder.startElement(COMMIT, null);

                builder.addAttribute(ID, commit.name());

                builder.endElement();
            }
            builder.endElement();

            if (merge.getConflicts() != null) {
                for (Entry<String, int[][]> entry : merge.getConflicts().entrySet()) {
                    builder.startElement(CHECKOUT_CONFLICT, null);
                    builder.addAttribute(PATH, entry.getKey());

                    builder.endElement();
                }

            }

            if (merge.getCheckoutConflicts() != null) {
                for (String path : merge.getCheckoutConflicts()) {
                    builder.startElement(CHECKOUT_CONFLICT, null);
                    builder.addAttribute(PATH, path);

                    builder.endElement();
                }
            }

            if (merge.getFailingPaths() != null) {
                for (Entry<String, MergeFailureReason> entry : merge.getFailingPaths().entrySet()) {
                    builder.startElement(FAILING_PATH, null);
                    builder.addAttribute(PATH, entry.getKey());
                    builder.addAttribute(REASON, entry.getValue().name());

                    builder.endElement();
                }
            }
        }

        RebaseResult rebase = answer.getRebaseResult();

        if (rebase != null) {
            builder.startElement(REBASE, null);
            builder.addAttribute(STATUS, rebase.getStatus().toString());
            builder.addAttribute(IS_SUCCESSFUL, Boolean.toString(rebase.getStatus().isSuccessful()));

            //rebase.getConflicts()

            if (rebase.getFailingPaths() != null) {
                for (Entry<String, MergeFailureReason> entry : rebase.getFailingPaths().entrySet()) {
                    builder.startElement(FAILING_PATH, null);
                    builder.addAttribute(PATH, entry.getKey());
                    builder.addAttribute(REASON, entry.getValue().name());

                    builder.endElement();
                }
            }
            builder.endElement();
        }

        return builder.getDocument().getNode(nodeNr);
    } catch (Throwable e) {
        e.printStackTrace();
        throw new XPathException(this, Module.EXGIT001, e);
    }
}

From source file:org.fusesource.fabric.itests.basic.git.FabricGitTestSupport.java

License:Apache License

/**
 * Create a profile in git and check that its bridged to the registry.
 *
 * @param git     The git object of the test repository.
 * @param version The version of the profile.
 * @param profile The profile name./*from   w w  w  .j ava  2 s  . co m*/
 * @throws Exception
 */
public void createAndTestProfileInGit(Git git, String version, String profile) throws Exception {
    //Create the test profile in git
    System.err.println("Create test profile:" + profile + " in git.");
    GitUtils.checkoutBranch(git, "origin", version);
    File testProfileDir = new File(git.getRepository().getWorkTree(), profile);
    testProfileDir.mkdirs();
    File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
    testProfileConfig.createNewFile();
    Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
    git.add().addFilepattern(profile).call();
    git.commit().setMessage("Create " + profile).call();
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
    GitUtils.waitForBranchUpdate(getCurator(), version);
    //Check that it has been bridged in zookeeper
    Thread.sleep(5000);
    assertNotNull(getCurator().checkExists().forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, profile)));
}