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:ezbake.deployer.publishers.openShift.RhcApplication.java

License:Apache License

/**
 * This will make sure that a directory is on disk for the git repository.  It will clone the git repo to the directory
 * if needed, or git pull the new contents if required.
 *
 * @return git repository created/retrieved from OpenShift with the remote pointing to OpenShift
 * @throws DeploymentException - on any exception getting it from git
 *///from  w  w  w. java 2 s .c  om
public Git getOrCreateGitRepo() throws DeploymentException {
    String gitUrl = applicationInstance.getGitUrl();

    Files.createDirectories(appTmpDir);
    File gitDir = new File(appTmpDir, ".git");
    if (gitRepo != null || gitDir.exists() && gitDir.isDirectory()) {
        try {
            Git git = gitRepo != null ? gitRepo : Git.open(appTmpDir);
            // stash to get to a clean state of git dir so that we can pull without conflicts
            git.stashCreate();
            git.stashDrop();
            PullCommand pullCommand = git.pull();
            if (gitCredentialsProvider != null)
                pullCommand.setCredentialsProvider(gitCredentialsProvider);
            PullResult result = pullCommand.call();
            if (!result.isSuccessful())
                throw new DeploymentException("Git pull was not successful: " + result.toString());
            setGitRepo(git);
            return git;
        } catch (IOException | GitAPIException e) {
            log.error("Error opening existing cached git repo", e);
            throw new DeploymentException("Error opening existing cached git repo: " + e.getMessage());
        }
    } else {
        try {
            log.info("Cloning to " + appTmpDir.toString());
            CloneCommand cloneCommand = Git.cloneRepository().setURI(gitUrl).setTimeout(10000)
                    .setDirectory(appTmpDir);
            if (gitCredentialsProvider != null)
                cloneCommand.setCredentialsProvider(gitCredentialsProvider);
            gitRepo = cloneCommand.call();
            log.info("Cloned to directory: "
                    + gitRepo.getRepository().getDirectory().getParentFile().getAbsolutePath());
            return gitRepo;
        } catch (GitAPIException | JGitInternalException e) {
            log.error("Error cloning repository from OpenShift", e);
            throw new DeploymentException("Error cloning repository from OpenShift: " + e.getMessage());
        }
    }
}

From source file:facade.GitFacade.java

public static String pullRepo(Repository repository) throws GitAPIException {
    Git git = new Git(repository);
    PullResult result = null;//w  ww.  j a  v  a  2s . c  o m
    org.eclipse.jgit.api.PullCommand pullComand = git.pull();
    result = pullComand.call();
    MergeResult mergeResult = result.getMergeResult();

    return "Merge Status: " + mergeResult.getMergeStatus().toString();

}

From source file:fi.otavanopisto.changelogger.Changelogger.java

private static void prependLine(String line, String message) throws IOException, GitAPIException {
    FileRepositoryBuilder frBuilder = new FileRepositoryBuilder();
    Repository repository = frBuilder.setGitDir(new File("./.git")).readEnvironment().build();
    Git git = new Git(repository);

    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    git.clean().call();/* w  w  w  . j  a  va  2  s. co  m*/
    git.fetch().call();
    git.pull().call();

    File file = new File(CHANGELOG_FILE);
    List<String> lines = FileUtils.readLines(file, Charsets.UTF_8);
    lines.add(0, line);
    FileUtils.writeLines(file, lines);

    git.commit().setMessage(message).setAuthor("Changelogger", "changelogger@otavanopisto.fi").call();

    git.push().call();
}

From source file:fi.otavanopisto.santra.Santra.java

License:Open Source License

private void reload(String botName) throws IOException, GitAPIException {
    log.info("Starting bot reload");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(arguments.getBasePath() + "/.git")).readEnvironment()
            .build();//  ww  w .  j  a v a2 s. c  o  m
    log.info("Starting repository update");
    Git git = new Git(repository);
    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    log.info("Reset complete");
    git.clean().call();
    log.info("Clean compete");
    git.fetch().call();
    log.info("Fetch complete");
    git.pull().call();
    log.info("Repository update finished");

    initBot(botName);
    log.info("Bot reloaded");
}

From source file:fr.duminy.tools.jgit.JGitToolbox.java

License:Open Source License

public String track(Parameters parameters) throws GitToolboxException {
    try {//  w  ww .  j  a  v  a 2s . c o  m
        Git targetGit = Git.open(parameters.getGitDirectory());
        ProgressMonitor progressMonitor = new TextProgressMonitor();
        PullCommand pullCommand = targetGit.pull().setProgressMonitor(progressMonitor);
        PullResult result = pullCommand.call();
        System.out.println(result);
        if (!result.isSuccessful()) {
            throw new GitToolboxException("Failed to update tracking branch : " + result.toString());
        }

        MergeResult.MergeStatus mergeStatus = result.getMergeResult().getMergeStatus();
        if (!ALREADY_UP_TO_DATE.equals(mergeStatus) && !FAST_FORWARD.equals(mergeStatus)) {
            throw new GitToolboxException("Failed to update tracking branch : " + result.toString());
        }

        return targetGit.getRepository().getRef(Constants.HEAD).getName();
    } catch (Exception e) {
        throw new GitToolboxException("Error while updating tracking branch", e);
    }
}

From source file:io.fabric8.collector.git.GitBuildConfigProcessor.java

License:Apache License

protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent,
        UserDetails userDetails) {//from   w ww  . j  a v a  2s  .  c  o m
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);

        File projectFolder = repository.getDirectory();

        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", userDetails.getRemote(), "url");
        if (Strings.isNullOrBlank(url)) {
            LOG.warn("No remote repository url for " + branch + " defined for the git repository at "
                    + projectFolder.getCanonicalPath() + " so cannot pull");
            //return;
        }
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
            LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at "
                    + projectFolder.getCanonicalPath() + " so not doing a pull");
            //return;
        }

        LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: "
                + url);
        PullCommand pull = git.pull();
        GitHelpers.configureCommand(pull, userDetails);
        pull.setRebase(true).call();
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage()
                + ". This exception is ignored.", e);
    }
}

From source file:io.fabric8.forge.generator.pipeline.JenkinsPipelineLibrary.java

License:Apache License

protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent,
        UserDetails userDetails) {// w  ww  .j ava2s. c om
    StopWatch watch = new StopWatch();
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);

        File projectFolder = repository.getDirectory();

        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remote, "url");
        if (io.fabric8.utils.Strings.isNullOrBlank(url)) {
            LOG.warn("No remote repository url for " + branch + " defined for the git repository at "
                    + projectFolder.getCanonicalPath() + " so cannot pull");
            //return;
        }
        String mergeUrl = config.getString("branch", branch, "merge");
        if (io.fabric8.utils.Strings.isNullOrBlank(mergeUrl)) {
            LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at "
                    + projectFolder.getCanonicalPath() + " so not doing a pull");
            //return;
        }

        // lets trash any failed changes
        LOG.debug("Stashing local changes to the repo");
        boolean hasHead = true;
        try {
            git.log().all().call();
            hasHead = git.getRepository().getAllRefs().containsKey("HEAD");
        } catch (NoHeadException e) {
            hasHead = false;
        }
        if (hasHead) {
            // lets stash any local changes just in case..
            try {
                git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                        .setRef("HEAD").call();
            } catch (Throwable e) {
                LOG.error("Failed to stash changes: " + e, e);
                Throwable cause = e.getCause();
                if (cause != null && cause != e) {
                    LOG.error("Cause: " + cause, cause);
                }
            }
        }

        //LOG.debug("Resetting the repo");
        //git.reset().setMode(ResetCommand.ResetType.HARD).call();

        LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: "
                + url);
        PullCommand pull = git.pull();
        GitUtils.configureCommand(pull, userDetails);
        pull.setRebase(true).call();
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage()
                + ". This exception is ignored.", e);
    } finally {
        LOG.debug("doPull took " + watch.taken());
    }
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected void doPull(Git git, GitContext context) throws GitAPIException {
    LOG.info("Performing a pull in git repository " + this.gitFolder + " on remote URL: "
            + this.remoteRepository);
    CredentialsProvider cp = userDetails.createCredentialsProvider();
    PullCommand command = git.pull();
    configureCommand(command, userDetails);
    command.setCredentialsProvider(cp).setRebase(true).call();
    LOG.info("Completed pull in git repository " + this.gitFolder + " on remote URL: " + this.remoteRepository);
}

From source file:io.fabric8.forge.rest.main.ProjectFileSystem.java

License:Apache License

protected void doPull(File gitFolder, CredentialsProvider cp, String branch) {
    try {/*from   ww  w .  j av  a 2s.c o m*/
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);

        File projectFolder = repository.getDirectory();

        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remote, "url");
        if (Strings.isNullOrBlank(url)) {
            LOG.warn("No remote repository url for " + branch + " defined for the git repository at "
                    + projectFolder.getCanonicalPath() + " so cannot pull");
            //return;
        }
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
            LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at "
                    + projectFolder.getCanonicalPath() + " so not doing a pull");
            //return;
        }

        // lets trash any failed changes
        LOG.info("Resetting the repo");
        git.reset().setMode(ResetCommand.ResetType.HARD).call();

        LOG.info("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: "
                + url);
        git.pull().setCredentialsProvider(cp).setRebase(true).call();
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage()
                + ". This exception is ignored.", e);
    }
}

From source file:io.fabric8.itests.basic.git.FabricGitTestSupport.java

License:Apache License

/**
 * Create a profile in git and check that its bridged to the registry.
 */// www .ja  va 2s .c o  m
protected void createAndTestProfileInGit(FabricService fabricService, CuratorFramework curator, Git git,
        String version, String profile) throws Exception {
    //Create the test profile in git
    System.out.println("Create test profile:" + profile + " in git.");
    GitUtils.checkoutBranch(git, "origin", version);
    String relativeProfileDir = "fabric/profiles/" + profile + ".profile";
    File testProfileDir = new File(git.getRepository().getWorkTree(), relativeProfileDir);
    testProfileDir.mkdirs();
    File testProfileConfig = new File(testProfileDir, "io.fabric8.agent.properties");
    testProfileConfig.createNewFile();
    Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
    git.add().addFilepattern(relativeProfileDir).call();
    git.commit().setAll(true).setMessage("Create " + profile).call();
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    git.push().setCredentialsProvider(getCredentialsProvider()).setPushAll().setRemote("origin").call();
    GitUtils.waitForBranchUpdate(curator, version);
    for (int i = 0; i < 5; i++) {
        if (fabricService.getDataStore().hasProfile(version, profile)) {
            return;
        } else {
            Thread.sleep(1000);
        }
    }
    fail("Expected to find profile " + profile + " in version " + version);
}