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

License:Apache License

/**
 * Create a profile in the registry and check that its bridged to git.
 *///from w w  w. j  a  v a  2  s  .com
protected void createAndTestProfileInDataStore(FabricService fabricService, CuratorFramework curator, Git git,
        String version, String profile) throws Exception {
    System.out.println("Create test profile:" + profile + " in datastore.");
    List<String> versions = Lists.transform(Arrays.<Version>asList(fabricService.getVersions()),
            new Function<Version, String>() {

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

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

    fabricService.getDataStore().createProfile(version, profile);
    GitUtils.waitForBranchUpdate(curator, version);
    GitUtils.checkoutBranch(git, "origin", version);
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    assertTrue(pullResult.isSuccessful());
    String relativeProfileDir = "fabric/profiles/" + profile + ".profile";
    File testProfileDir = new File(git.getRepository().getWorkTree(), relativeProfileDir);
    assertTrue(testProfileDir.exists());
    File testProfileConfig = new File(testProfileDir, "io.fabric8.agent.properties");
    assertTrue(testProfileConfig.exists());
}

From source file:io.github.thefishlive.updater.Updater.java

License:Open Source License

public void run() {
    System.out.println("-------------------------");
    System.out.println(gitDir.getAbsolutePath());
    File updateFile = new File(basedir, "UPDATE");
    Git git = null;

    try {//from  w w w  .  j  ava 2 s. c o  m
        if (!gitDir.exists()) {
            git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote)
                    .setProgressMonitor(buildProgressMonitor()).call();

            System.out.println("Repository cloned");
        } else {
            updateFile.createNewFile();

            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repo = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                    .findGitDir() // scan up the file system tree
                    .build();

            git = new Git(repo);

            PullResult result = git.pull().setProgressMonitor(buildProgressMonitor()).call();

            if (!result.isSuccessful() || result.getMergeResult().getMergeStatus().equals(MergeStatus.MERGED)) {
                System.out.println("Update Failed");
                FileUtils.deleteDirectory(basedir);
                basedir.mkdir();
                System.out.println("Re-cloning repository");

                git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote)
                        .setProgressMonitor(buildProgressMonitor()).call();

                System.out.println("Repository cloned");
            }

            System.out.println("State: " + result.getMergeResult().getMergeStatus());
        }

        File configdir = new File("config");

        if (configdir.exists()) {
            FileUtils.copyDirectory(configdir, new File(basedir, "config"));
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        git.getRepository().close();
    }

    updateFile.delete();
    System.out.println("-------------------------");
}

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

License:Apache License

private Git initializeGit() throws IOException, GitAPIException {
    if (path.isDirectory()) {
        Git git = Git.open(path);
        String current = git.getRepository().getBranch();
        if (branch.equalsIgnoreCase(current)) {
            PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider)
                    .setTransportConfigCallback(transportConfigCallback).call();
            if (!pull.isSuccessful()) {
                LOGGER.warn("Unable to pull the branch + '" + branch + "' from the remote repository '" + remote
                        + "'");
            }//from w  ww. ja  v  a2s  .  c  o  m
            return git;
        } else {
            git.checkout().setName(branch).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                    .setStartPoint(remote + "/" + branch).call();
            return git;
        }
    } else {
        return Git.cloneRepository().setURI(url).setBranch(branch).setRemote(remote).setDirectory(path)
                .setCredentialsProvider(credentialProvider).setTransportConfigCallback(transportConfigCallback)
                .call();
    }
}

From source file:licenseUtil.Utils.java

License:Apache License

public static void updateRepository(String gitDir) {
    try {//from  w w  w  .jav  a2s  .c  o m
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);

        git.pull().call();
    } catch (GitAPIException e) {
        logger.warn("Could not update local repository: \"" + gitDir + "\" with git pull.");
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}

From source file:net.orpiske.ssps.common.scm.git.GitSCM.java

License:Apache License

private void update(final File repositoryDir) throws ScmUpdateException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository;/*w ww  .  j  a  v a 2 s. c  o m*/

    try {
        repository = builder.setGitDir(repositoryDir).readEnvironment().findGitDir().build();
    } catch (IOException e) {
        throw new ScmUpdateException(e.getMessage(), e);
    }

    Git git = new Git(repository);
    PullCommand pullCommand = git.pull();

    pullCommand.setProgressMonitor(new TextProgressMonitor());

    try {
        pullCommand.call();
    } catch (Exception e) {
        e.printStackTrace();

        throw new ScmUpdateException(e.getMessage(), e);
    }
}

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

License:Open Source License

protected String upgrade(String path) throws Exception {
    //staticDir.mkdirs();
    Repository repository = null;//from  w  w w .j a v a  2  s . co  m
    try {
        String logFile = "output.log";
        File installLogDir = new File(staticDir, "logs");
        installLogDir.mkdirs();
        //
        File destDir = new File(staticDir, SLASH + path);
        destDir.mkdirs();
        File output = new File(installLogDir, logFile);
        String gitPath = github + path + ".git";
        logger.debug("Updating from " + gitPath + " to " + destDir.getAbsolutePath());
        FileUtils.writeStringToFile(output,
                "Updating from " + gitPath + " to " + destDir.getAbsolutePath() + "\n", false);
        Git git = null;
        try {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            repository = builder.setGitDir(new File(destDir, "/.git")).readEnvironment() // scan environment GIT_* variables
                    .findGitDir() // scan up the file system tree
                    .build();
            git = new Git(repository);
            PullResult result = git.pull().call();
            FileUtils.writeStringToFile(output, result.getMergeResult().toString(), true);
            logger.debug("DONE: Updated " + gitPath + " repository: " + result.getMergeResult().toString());

            //now run npm install
            //runNpmInstall(output, destDir);
        } catch (Exception e) {
            FileUtils.writeStringToFile(output, e.getMessage(), true);
            FileUtils.writeStringToFile(output, e.getStackTrace().toString(), true);
            logger.debug("Error updating " + gitPath + " repository: " + e.getMessage(), e);
        } finally {
            if (git != null)
                git.close();
            if (repository != null)
                repository.close();
        }
        return logFile;

    } finally {
        if (repository != null)
            repository.close();
    }

}

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

License:Apache License

/**
 * For git, the given repository is a remote one. We have to clone it first if the working directory does not
 * contain a git repo yet, otherwise we have to git-pull it.
 * <p/>/* w ww.j  av  a  2  s. c  o m*/
 * {@inheritDoc}
 */
protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet,
        ScmVersion version, boolean recursive) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;

    if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol())
            && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) {
        throw new ScmException("remote repository must not be the working directory");
    }

    Git git = null;
    try {

        ProgressMonitor monitor = JGitUtils.getMonitor(getLogger());

        String branch = version != null ? version.getName() : null;

        if (StringUtils.isBlank(branch)) {
            branch = Constants.MASTER;
        }

        getLogger().debug("try checkout of branch: " + branch);

        if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) {
            if (fileSet.getBasedir().exists()) {
                // git refuses to clone otherwise
                fileSet.getBasedir().delete();
            }

            // FIXME only if windauze
            WindowCacheConfig cfg = new WindowCacheConfig();
            cfg.setPackedGitMMAP(false);
            cfg.install();

            // no git repo seems to exist, let's clone the original repo
            CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo);
            getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir());
            CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl());
            command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir());
            command.setProgressMonitor(monitor);
            git = command.call();
        }

        JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand();
        remoteInfoCommand.setLogger(getLogger());
        RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null);

        if (git == null) {
            git = Git.open(fileSet.getBasedir());
        }

        if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists()
                && result.getBranches().size() > 0) {
            // git repo exists, so we must git-pull the changes
            CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository);

            if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) {
                // A tag will not be pulled but we only fetch all the commits from the upstream repo
                // This is done because checking out a tag might not happen on the current branch
                // but create a 'detached HEAD'.
                // In fact, a tag in git may be in multiple branches. This occurs if
                // you create a branch after the tag has been created
                getLogger().debug("fetch...");
                git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            } else {
                getLogger().debug("pull...");
                git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            }
        }

        Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git);
        if (version instanceof ScmTag) {
            getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else if (localBranchNames.contains(branch)) {
            getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else {
            getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).setCreateBranch(true)
                    .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call();
        }

        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD));
        revWalk.release();

        final TreeWalk walk = new TreeWalk(git.getRepository());
        walk.reset(); // drop the first empty tree, which we do not need here
        walk.setRecursive(true);
        walk.addTree(commit.getTree());

        List<ScmFile> listedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        getLogger().debug("current branch: " + git.getRepository().getBranch());

        return new CheckOutScmResult("checkout via JGit", listedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkout failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.openaz.xacml.admin.view.windows.GitSynchronizeWindow.java

License:Apache License

protected void synchronize() {
    ////from   w  w  w.  j  av  a 2  s  .co  m
    // Grab our working repository
    //
    Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
    try {
        final Git git = Git.open(repoPath.toFile());

        PullResult result = git.pull().call();
        // FetchResult fetch = result.getFetchResult();
        // MergeResult merge = result.getMergeResult();
        // RebaseResult rebase = result.getRebaseResult();
        if (result.isSuccessful()) {
            //
            // TODO add more notification
            //
            this.textAreaResults.setValue("Successful!");
        } else {
            //
            // TODO
            //
            this.textAreaResults.setValue("Failed.");
        }
    } catch (IOException | GitAPIException e) {
        e.printStackTrace();
    }
    this.buttonSynchronize.setCaption("Ok");
}

From source file:org.apache.sshd.git.pack.GitPackCommandTest.java

License:Apache License

@Test
public void testGitPack() throws Exception {
    Assume.assumeFalse("On windows this activates TortoisePlink", OsUtils.isWin32());

    Path targetParent = detectTargetFolder().getParent();
    Path gitRootDir = getTempTargetRelativeFile(getClass().getSimpleName());

    try (SshServer sshd = setupTestServer()) {
        Path serverRootDir = gitRootDir.resolve("server");
        sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshd.setCommandFactory(//from www .j a v a  2  s . co  m
                new GitPackCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverRootDir)));
        sshd.start();

        int port = sshd.getPort();
        try {
            Path serverDir = serverRootDir.resolve("test.git");
            Utils.deleteRecursive(serverDir);
            Git.init().setBare(true).setDirectory(serverDir.toFile()).call();

            JSch.setConfig("StrictHostKeyChecking", "no");
            CredentialsProvider.setDefault(
                    new UsernamePasswordCredentialsProvider(getCurrentTestName(), getCurrentTestName()));
            SshSessionFactory.setInstance(new GitSshdSessionFactory());

            Path localRootDir = gitRootDir.resolve("local");
            Path localDir = localRootDir.resolve(serverDir.getFileName());
            Utils.deleteRecursive(localDir);
            Git.cloneRepository().setURI("ssh://" + getCurrentTestName() + "@" + TEST_LOCALHOST + ":" + port
                    + "/" + serverDir.getFileName()).setDirectory(localDir.toFile()).call();

            Git git = Git.open(localDir.toFile());
            git.commit().setMessage("First Commit").setCommitter(getCurrentTestName(), "sshd@apache.org")
                    .call();
            git.push().call();

            Path readmeFile = Files.createFile(localDir.resolve("readme.txt"));
            git.add().addFilepattern(readmeFile.getFileName().toString()).call();
            git.commit().setMessage(getCurrentTestName()).setCommitter(getCurrentTestName(), "sshd@apache.org")
                    .call();
            git.push().call();

            git.pull().setRebase(true).call();
        } finally {
            sshd.stop();
        }
    }
}

From source file:org.craftercms.deployer.impl.processors.GitPullProcessor.java

License:Open Source License

protected ChangeSet pullChanges(Git git) {
    try {//  w  w w  .ja  v a  2  s  . c  om
        logger.info("Executing git pull for repository {}...", localRepositoryFolder);

        ObjectId head = git.getRepository().resolve(Constants.HEAD);
        PullResult pullResult = git.pull().call();

        if (pullResult.isSuccessful()) {
            MergeResult mergeResult = pullResult.getMergeResult();
            switch (mergeResult.getMergeStatus()) {
            case FAST_FORWARD:
                logger.info("Changes successfully pulled from remote {} for repository {}. Processing them...",
                        remoteRepositoryUrl, localRepositoryFolder);

                return resolveChangeSetFromPull(git, head, mergeResult.getNewHead());
            case ALREADY_UP_TO_DATE:
                logger.info("Git repository {} up to date (no changes pulled from remote {})",
                        localRepositoryFolder, remoteRepositoryUrl);
                return new ChangeSetImpl();
            default:
                // Not supported merge results
                throw new DeploymentException("Received unsupported merge result after executing pull command: "
                        + mergeResult.getMergeStatus());
            }
        }
    } catch (Exception e) {
        throw new DeploymentException("Git pull for repository " + localRepositoryFolder + " failed", e);
    }

    return new ChangeSetImpl();
}