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.fusesource.fabric.itests.basic.git.FabricGitTestSupport.java

License:Apache License

/**
 * Create a profile in the registry and check that its bridged to git.
 *
 * @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.ja v  a  2 s .co m
 * @throws Exception
 */
public void createAndTestProfileInZooKeeper(Git git, String version, String profile) throws Exception {
    System.err.println("Create test profile:" + profile + " in zookeeper.");
    List<String> versions = Lists.transform(Arrays.<Version>asList(getFabricService().getVersions()),
            new Function<Version, String>() {

                @Override
                public String apply(Version version) {
                    return version.getId();
                }
            });

    if (!versions.contains(version)) {
        getFabricService().createVersion(version);
    }

    getFabricService().getVersion(version).createProfile(profile);
    GitUtils.waitForBranchUpdate(getCurator(), version);
    Thread.sleep(5000);
    GitUtils.checkoutBranch(git, "origin", version);
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    assertTrue(pullResult.isSuccessful());
    File testProfileDir = new File(git.getRepository().getWorkTree(), profile);
    assertTrue(testProfileDir.exists());
    File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
    assertTrue(testProfileConfig.exists());
}

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

License:Apache License

public void testWithProfiles() throws Exception {
    String testProfileNameBase = "mytestprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult()
            .build();/*www  . j a va 2 s  .  c  o  m*/
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());

    GitUtils.waitForBranchUpdate(getCurator(), "1.0");

    Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo)
            .setCredentialsProvider(getCredentialsProvider()).call();
    Git git = Git.open(testrepo);
    GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0");
    git.fetch().setCredentialsProvider(getCredentialsProvider());
    GitUtils.checkoutBranch(git, "origin", "1.0");

    //Check that the default profile exists
    assertTrue(new File(testrepo, "default").exists());

    //Create test profile
    for (int i = 1; i <= 3; i++) {
        String testProfileName = testProfileNameBase + i;
        System.err.println("Create test profile:" + testProfileName + " in zookeeper");
        getFabricService().getVersion("1.0").createProfile(testProfileName);
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        git.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call();
        //Check that a newly created profile exists
        assertTrue(new File(testrepo, testProfileName).exists());
        //Delete test profile
        System.err.println("Delete test profile:" + testProfileName + " in git.");
        git.rm().addFilepattern(testProfileName).call();
        git.commit().setMessage("Delete " + testProfileName).call();
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        Thread.sleep(5000);
        assertFalse(new File(testrepo, testProfileName).exists());
        assertNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));

        //Create the test profile in git
        System.err.println("Create test profile:" + testProfileName + " in git.");
        File testProfileDir = new File(testrepo, testProfileName);
        testProfileDir.mkdirs();
        File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
        testProfileConfig.createNewFile();
        Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
        git.add().addFilepattern(testProfileName).call();
        RevCommit commit = git.commit().setMessage("Create " + testProfileName).call();
        FileTreeIterator fileTreeItr = new FileTreeIterator(git.getRepository());
        IndexDiff indexDiff = new IndexDiff(git.getRepository(), commit.getId(), fileTreeItr);
        System.out.println(indexDiff.getChanged());
        System.out.println(indexDiff.getAdded());
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        //Check that it has been bridged in zookeeper
        Thread.sleep(15000);
        assertNotNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));
    }
}

From source file:org.jboss.forge.addon.git.GitUtilsImpl.java

License:Open Source License

@Override
public PullResult pull(final Git git, final int timeout) throws GitAPIException {
    PullCommand pull = git.pull();
    if (timeout >= 0)
        pull.setTimeout(timeout);//from w w w .jav  a  2 s  . c  o m
    pull.setProgressMonitor(new TextProgressMonitor());

    PullResult result = pull.call();
    return result;
}

From source file:org.jboss.forge.git.GitUtils.java

License:Open Source License

public static PullResult pull(final Git git, final int timeout) throws GitAPIException {
    PullCommand pull = git.pull();
    if (timeout >= 0)
        pull.setTimeout(timeout);//from   w  w  w  . j  a  v  a  2 s .c  o m
    pull.setProgressMonitor(new TextProgressMonitor());

    PullResult result = pull.call();
    return result;
}

From source file:org.jdamico.jgitbkp.components.ManagerComponent.java

License:Open Source License

public void cloneRepos(List<RepoImpl> reposLst, Config config) throws JGitBackupException {

    for (int i = 0; i < reposLst.size(); i++) {

        File f = new File(reposLst.get(i).getClonedPath());

        if (f.mkdir()) {

            try {
                Git.cloneRepository().setCloneAllBranches(true).setCloneSubmodules(true).setNoCheckout(false)
                        .setURI(config.getProtocol() + "://" + config.getHostPath() + "/"
                                + reposLst.get(i).getName())
                        .setCredentialsProvider(
                                new UsernamePasswordCredentialsProvider(config.getUser(), config.getPasswd()))
                        .setDirectory(new File(reposLst.get(i).getClonedPath()))
                        .setProgressMonitor(new TextProgressMonitor()).call();

            } catch (InvalidRemoteException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            } catch (TransportException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            } catch (GitAPIException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            }//from w  w w.  j  ava 2 s.c  o m

        } else {
            try {
                Git git = Git.open(f);
                git.pull();
                LoggerManager.getInstance().logAtDebugTime(this.getClass().getName(),
                        "Updating data from repository.");
            } catch (IOException e) {
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), e.getMessage());
                throw new JGitBackupException(e);
            }
            String err = "Unable to create directory for clone [" + reposLst.get(i).getName()
                    + "]. Check the path and permissions.";
            if (!f.exists()) {
                if (!Starter.silent)
                    System.out.println(err);
                LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err);
            }

        }
    }

}

From source file:org.jdamico.jgitbkp.components.ManagerComponent.java

License:Open Source License

public List<BundleStatus> generateBundles(List<RepoImpl> reposLst, Config config) throws JGitBackupException {

    List<BundleStatus> bundleStatusLst = new ArrayList<BundleStatus>();

    boolean backupStatus = false;
    StringBuffer backupMessage = new StringBuffer();

    for (int i = 0; i < reposLst.size(); i++) {
        String bundlePath = config.getBundlePath() + "/" + reposLst.get(i).getName() + ".bundle";

        File gitWorkDir = new File(reposLst.get(i).getClonedPath());
        Git git = null;
        Repository localRepoGit = null;//www  .  j  a v a2  s  .c o  m
        BundleWriter bundleWriter = null;
        ProgressMonitor pMonitor = null;
        OutputStream oStream = null;
        try {
            git = Git.open(gitWorkDir);
            git.pull();
            if (!Starter.silent)
                System.out.println("Updated data for [" + reposLst.get(i).getName() + "]");
            localRepoGit = git.getRepository();
            bundleWriter = new BundleWriter(localRepoGit);
            pMonitor = new TextProgressMonitor();
            oStream = new FileOutputStream(bundlePath);
            Map<String, Ref> allRefs = localRepoGit.getAllRefs();
            Collection<Ref> values = allRefs.values();
            Iterator<Ref> iter = values.iterator();
            while (iter.hasNext()) {
                try {
                    Ref element = iter.next();
                    bundleWriter.include(element);
                } catch (IllegalArgumentException e) {

                    if (!e.getMessage().equalsIgnoreCase("Invalid ref name: HEAD")) {
                        String err = reposLst.get(i).getName() + ": " + e.getMessage();
                        backupMessage.append(err);
                        LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err);
                    }
                }

            }
            if (!Starter.silent)
                bundleWriter.writeBundle(pMonitor, oStream);
            else
                bundleWriter.writeBundle(null, oStream);

        } catch (IOException e) {
            String err = reposLst.get(i).getName() + ": " + e.getMessage();
            backupMessage.append(err);
            LoggerManager.getInstance().logAtExceptionTime(this.getClass().getName(), err);
            throw new JGitBackupException(e);
        }

        File f = new File(bundlePath);
        if (f.exists() && f.length() > 100) {
            backupStatus = f.exists();
        } else
            backupStatus = false;

        bundleStatusLst.add(new BundleStatus(reposLst.get(i).getName(), backupStatus, backupMessage.toString(),
                Utils.getInstance().getCurrentDateTimeFormated(Constants.DATE_FORMAT), bundlePath));
        if (!Starter.silent)
            System.out.println("Bundle created: " + bundlePath + " - " + backupStatus);
    }

    return bundleStatusLst;
}

From source file:org.jdamico.jgitbkp.tests.JGitTester.java

License:Open Source License

@Test
public void test() throws IOException, GitAPIException {

    String user = "";
    String passwd = "";
    String hostPath = "/git";
    String backupRoot = "/tmp/test";
    String gitRoot = "/mnt";
    String bundlePath = "/tmp";
    boolean keepOld = false;

    List<org.jdamico.jgitbkp.entities.RepoImpl> repos = new ArrayList<org.jdamico.jgitbkp.entities.RepoImpl>();

    File fGitRoot = new File(gitRoot);
    String[] fRepos = fGitRoot.list();
    for (String itemRepo : fRepos) {
        File fItemRepo = new File(gitRoot + "/" + itemRepo);
        if (fItemRepo.isDirectory() && itemRepo.contains(".git") && !itemRepo.equals(".git")) {
            repos.add(new org.jdamico.jgitbkp.entities.RepoImpl(itemRepo, null, backupRoot + "/" + itemRepo));
        }//from  w  ww.  ja va  2s  . c  om
    }

    for (int i = 0; i < repos.size(); i++) {

        File f = new File(repos.get(i).getClonedPath());

        if (f.mkdir()) {

            Git.cloneRepository().setCloneAllBranches(true)
                    .setURI("http://" + hostPath + "/" + repos.get(i).getName())
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, passwd))
                    .setDirectory(new File(repos.get(i).getClonedPath()))
                    .setProgressMonitor(new TextProgressMonitor()).call();

        }

        File gitWorkDir = new File(repos.get(i).getClonedPath());
        Git git = Git.open(gitWorkDir);
        git.pull();
        Repository localRepoGit = git.getRepository();
        BundleWriter bundleWriter = new BundleWriter(localRepoGit);
        ProgressMonitor pMonitor = new TextProgressMonitor();
        OutputStream oStream = new FileOutputStream(bundlePath + "/" + repos.get(i).getName() + ".bundle");

        Map<String, Ref> allRefs = localRepoGit.getAllRefs();
        Collection<Ref> values = allRefs.values();
        Iterator<Ref> iter = values.iterator();
        while (iter.hasNext()) {
            Ref element = iter.next();
            try {

                bundleWriter.include(element);
                System.out.println("Added: " + element.getName());
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        bundleWriter.writeBundle(pMonitor, oStream);

    }

}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatabilityTestIT.java

/**
 * Git Plugin//from   w w  w.  j av  a  2s .  c o m
 *
 * Test that show that a ready/feature_1 branch get integrated into master
 * using a Matrix job type.
 *
 * Pretested integration:
 *  - 'Integration branch' : master (default)
 *  - 'Repository name' : origin (default) 
 *  - 'Strategy' : Squash Commit
 *
 * GitSCM:
 *  - 'Name' : (empty)
 *
 * Workflow
 *  - Create a repository containing a 'ready' branch.
 *  - The build is triggered. 
 *
 * Results
 *  - We expect that the plugin triggers, and that the commits on ready branch
 *    is merged into our integration branch master and build result becomes SUCCESS.
 *
 * @throws Exception
 */
@Test
public void oneBuildBasicSmokeTest() throws Exception {
    repository = TestUtilsFactory.createValidRepository("test-repo");

    File workDir = new File("test-repo");

    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();

    Git git = Git.open(workDir);

    System.out.println("Opening git repository in: " + workDir.getAbsolutePath());

    String readmeFromIntegration = FileUtils.readFileToString(new File("test-repo/readme"));

    git.checkout().setName(FEATURE_BRANCH_NAME).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
            .setCreateBranch(true).call();
    final int COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION = TestUtilsFactory.countCommits(git);
    git.checkout().setName("master").setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();

    GitProjectBuilder builder = new GitProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(GitProjectBuilder.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);

    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);

    jenkinsRule.waitUntilNoActivityUpTo(60000);

    assertEquals("2 runs for this particular matrix build", 2, project.getLastBuild().getRuns().size());

    String readmeFileContents = FileUtils.readFileToString(new File("test-repo/readme"));
    assertEquals(readmeFromIntegration, readmeFileContents);

    git.pull().call();

    final int COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION = TestUtilsFactory.countCommits(git);

    git.close();

    //We assert that 2 commits from branch gets merged + 1 combined merge commit since we do --no-ff
    assertEquals(COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION + 3, COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION);
}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatibilityTestIT.java

/**
 * Git Plugin//from w ww.j av  a  2s  .c  om
 *
 * Test that show that a ready/feature_1 branch get integrated into master
 * using a Matrix job type.
 *
 * Pretested integration:
 *  - 'Integration branch' : master (default)
 *  - 'Repository name' : origin (default)
 *  - 'Strategy' : Squash Commit
 *
 * GitSCM:
 *  - 'Name' : (empty)
 *
 * Workflow
 *  - Create a repository containing a 'ready' branch.
 *  - The build is triggered.
 *
 * Results
 *  - We expect that the plugin triggers, and that the commits on ready branch
 *    is merged into our integration branch master and build result becomes SUCCESS.
 *
 * @throws Exception
 */

@Test
public void oneBuildBasicSmokeTest() throws Exception {
    repository = TestUtilsFactory.createValidRepository("test-repo");
    File workDir = new File(TestUtilsFactory.WORKDIR, "test-repo");
    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();

    Git git = Git.open(workDir);

    System.out.println("Opening git repository in: " + workDir.getAbsolutePath());

    String readmeFromIntegration = FileUtils.readFileToString(new File(workDir, "readme"));

    git.checkout().setName(FEATURE_BRANCH_NAME).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
            .setCreateBranch(true).call();
    final int COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION = TestUtilsFactory.countCommits(git);
    git.checkout().setName("master").setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();

    MatrixProjectBuilder builder = new MatrixProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(TestUtilsFactory.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);

    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);

    jenkinsRule.waitUntilNoActivityUpTo(60000);

    String readmeFileContents = FileUtils.readFileToString(new File(workDir, "readme"));
    assertEquals(readmeFromIntegration, readmeFileContents);
    git.pull().call();

    assertEquals("3 runs for this particular matrix build", 3, project.getLastBuild().getRuns().size());

    final int COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION = TestUtilsFactory.countCommits(git);
    git.close();
    //We assert that 2 commits from branch gets merged + 1 combined merge commit since we do --no-ff
    assertEquals(COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION + 3, COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION);
}

From source file:org.kie.workbench.common.project.migration.cli.maven.PomEditorWithGitTest.java

License:Apache License

@Test
public void testPomEditor() throws Exception {
    final String repoName = "myrepoxxxx";
    HashMap<String, Object> env = new HashMap<>();
    env.put("init", Boolean.TRUE);
    env.put("internal", Boolean.TRUE);
    final JGitFileSystem fs = (JGitFileSystem) ioService.newFileSystem(URI.create("git://" + repoName), env);

    ioService.startBatch(fs);//from  ww  w. j  a  v a2s. c  o  m
    ioService.write(fs.getPath("/pom.xml"), new String(
            java.nio.file.Files.readAllBytes(new File("src/test/projects/generic/pom.xml").toPath())));
    ioService.endBatch();

    Path tmpCloned = Files.createTempDirectory("cloned");
    final File gitClonedFolder = new File(tmpCloned.toFile(), ".clone.git");

    final Git cloned = Git.cloneRepository()
            .setURI(fs.getGit().getRepository().getDirectory().toURI().toString()).setBare(false)
            .setDirectory(gitClonedFolder).call();

    assertNotNull(cloned);

    Path pomPath = Paths.get("file://" + gitClonedFolder.toString() + "/pom.xml");
    byte[] encoded = Files.readAllBytes(pomPath);
    String pomOriginal = new String(encoded, StandardCharsets.UTF_8);

    Model model = editor.updatePom(pomPath, cdiWrapper);
    assertNotNull(model);

    PullCommand pc = cloned.pull().setRemote("origin").setRebase(Boolean.TRUE);
    PullResult pullRes = pc.call();
    assertEquals(pullRes.getRebaseResult().getStatus(), RebaseResult.Status.UP_TO_DATE);

    RebaseCommand rb = cloned.rebase().setUpstream("origin/master");
    RebaseResult rbResult = rb.setPreserveMerges(true).call();
    assertTrue(rbResult.getStatus().isSuccessful());

    pomPath = Paths.get("file://" + gitClonedFolder.toString() + "/pom.xml");
    encoded = Files.readAllBytes(pomPath);
    String pomUpdated = new String(encoded, StandardCharsets.UTF_8);

    assertFalse(pomOriginal.equals(pomUpdated));
}