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:ch.sbb.releasetrain.git.GitRepoImpl.java

License:Apache License

private Git pull(Git git) throws GitAPIException {
    if (remoteBranchExists(git)) {
        PullResult result = git.pull().setStrategy(MergeStrategy.RECURSIVE)
                .setCredentialsProvider(this.credentialsProvider()).call();
        if (result.isSuccessful()) {
            return git;
        } else {/*from   w w  w  . j  a va2  s . c o m*/
            log.info(
                    "*** pulling git, not able to merge with MergeStrategy.RECURSIVE go for MergeStrategy.THEIRS");
            result = git.pull().setStrategy(MergeStrategy.THEIRS)
                    .setCredentialsProvider(this.credentialsProvider()).call();
            if (result.isSuccessful()) {
                return git;
            }
            throw new GitException("Pull failed: " + result.toString());
        }
    } else {
        return git;
    }
}

From source file:com.barchart.jenkins.cascade.PluginScmGit.java

License:BSD License

/**
 * See {@link Git#pull()}/*from   w w  w .jav  a 2 s .c  o m*/
 */
public static PullResult doPull(final File workspace) {
    try {
        final Git git = Git.open(workspace);
        return git.pull().call();
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

@Override
public File cloneRepoToDirectory(Application application, File dirLocation) {

    if (dirLocation.exists()) {
        File gitDirectoryFile = new File(dirLocation.getAbsolutePath() + File.separator + ".git");

        try {/*from  ww w.j  a va  2  s  .  c om*/
            if (!gitDirectoryFile.exists()) {
                Git newRepo = clone(application, dirLocation);
                if (newRepo != null)
                    return newRepo.getRepository().getWorkTree();
            } else {
                Repository localRepo = new FileRepository(gitDirectoryFile);
                Git git = new Git(localRepo);

                if (application.getRepositoryRevision() != null
                        && !application.getRepositoryRevision().isEmpty()) {
                    //remote checkout
                    git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision())
                            .setName(application.getRepositoryRevision()).call();
                } else {

                    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();

                    String repoBranch = (application.getRepositoryBranch() != null
                            && !application.getRepositoryBranch().isEmpty()) ? application.getRepositoryBranch()
                                    : "master";

                    boolean localCheckout = false;

                    for (Ref ref : refs) {
                        String refName = ref.getName();
                        if (refName.contains(repoBranch) && !refName.contains(Constants.R_REMOTES)) {
                            localCheckout = true;
                        }
                    }

                    String HEAD = localRepo.getFullBranch();

                    if (HEAD.contains(repoBranch)) {
                        git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                .setCredentialsProvider(getApplicationCredentials(application)).call();
                    } else {
                        if (localCheckout) {
                            //local checkout
                            git.checkout().setName(application.getRepositoryBranch()).call();
                            git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                    .setCredentialsProvider(getApplicationCredentials(application)).call();
                        } else {
                            //remote checkout
                            git.checkout().setCreateBranch(true).setName(repoBranch)
                                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                                    .setStartPoint("origin/" + repoBranch).call();
                        }
                    }
                }

                return git.getRepository().getWorkTree();
            }
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (IOException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (WrongRepositoryStateException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidConfigurationException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (DetachedHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRemoteException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CanceledException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefNotFoundException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (NoHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefAlreadyExistsException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CheckoutConflictException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRefNameException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (TransportException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (GitAPIException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    } else {
        try {
            log.info("Attempting to clone application from repository.");
            Git result = clone(application, dirLocation);
            if (result != null) {
                log.info("Application was successfully cloned from repository.");
                return result.getRepository().getWorkTree();
            }
            log.error(EXCEPTION_MESSAGE);
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    }
    return null;
}

From source file:com.door43.translationstudio.tasks.PullTargetTranslationTask.java

private String pull(Repo repo, String remote) {
    Git git;
    try {//from  w  ww  .  jav a 2s .com
        repo.deleteRemote("origin");
        repo.setRemote("origin", remote);
        git = repo.getGit();
    } catch (IOException e) {
        return null;
    }

    Manifest localManifest = Manifest.generate(this.targetTranslation.getPath());

    // TODO: we might want to get some progress feedback for the user
    PullCommand pullCommand = git.pull().setTransportConfigCallback(new TransportCallback()).setRemote("origin")
            .setStrategy(mergeStrategy).setRemoteBranchName("master").setProgressMonitor(new ProgressMonitor() {
                @Override
                public void start(int totalTasks) {

                }

                @Override
                public void beginTask(String title, int totalWork) {

                }

                @Override
                public void update(int completed) {

                }

                @Override
                public void endTask() {

                }

                @Override
                public boolean isCancelled() {
                    return false;
                }
            });
    try {
        PullResult result = pullCommand.call();
        MergeResult mergeResult = result.getMergeResult();
        if (mergeResult != null && mergeResult.getConflicts() != null
                && mergeResult.getConflicts().size() > 0) {
            this.status = Status.MERGE_CONFLICTS;
            this.conflicts = mergeResult.getConflicts();

            // revert manifest merge conflict to avoid corruption
            if (this.conflicts.containsKey("manifest.json")) {
                Logger.i("PullTargetTranslationTask", "Reverting to server manifest");
                try {
                    git.checkout().setStage(CheckoutCommand.Stage.THEIRS).addPath("manifest.json").call();
                    Manifest remoteManifest = Manifest.generate(this.targetTranslation.getPath());
                    localManifest = TargetTranslation.mergeManifests(localManifest, remoteManifest);
                } catch (CheckoutConflictException e) {
                    // failed to reset manifest.json
                    Logger.e(this.getClass().getName(), "Failed to reset manifest: " + e.getMessage(), e);
                } finally {
                    localManifest.save();
                }
            }

            // keep our license
            if (this.conflicts.containsKey("LICENSE.md")) {
                Logger.i("PullTargetTranslationTask", "Reverting to local license");
                try {
                    git.checkout().setStage(CheckoutCommand.Stage.OURS).addPath("LICENSE.md").call();
                } catch (CheckoutConflictException e) {
                    Logger.e(this.getClass().getName(), "Failed to reset license: " + e.getMessage(), e);
                }
            }
        } else {
            this.status = Status.UP_TO_DATE;
        }

        return "message";
    } catch (TransportException e) {
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        Throwable cause = e.getCause();
        if (cause != null) {
            Throwable subException = cause.getCause();
            if (subException != null) {
                String detail = subException.getMessage();
                if ("Auth fail".equals(detail)) {
                    this.status = Status.AUTH_FAILURE; // we do special handling for auth failure
                }
            } else if (cause instanceof NoRemoteRepositoryException) {
                this.status = Status.NO_REMOTE_REPO;
            }
        }
        return null;
    } catch (Exception e) {
        Throwable cause = e.getCause();
        if (cause instanceof NoRemoteRepositoryException) {
            this.status = Status.NO_REMOTE_REPO;
        }
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        return null;
    } catch (OutOfMemoryError e) {
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        this.status = Status.OUT_OF_MEMORY;
        return null;
    } catch (Throwable e) {
        Logger.e(this.getClass().getName(), e.getMessage(), e);
        return null;
    }
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

License:Apache License

/**
 * This method is used to clone repository from github using the URL and branch to local destination folder.
 * /*  w ww  . j a v a2 s  .c  om*/
 * @param repoURL
 *            repository url to clone.
 * @param branch
 *            specific branch name of the repository to clone
 * @param localEiffelRepoPath
 *            destination path to clone the repo.
 */
private void cloneEiffelRepo(final String repoURL, final String branch, final File localEiffelRepoPath) {
    Git localGitRepo = null;

    // checking for repository exists or not in the localEiffelRepoPath
    try {
        if (!localEiffelRepoPath.exists()) {
            // cloning github repository by using URL and branch name into local
            localGitRepo = Git.cloneRepository().setURI(repoURL).setBranch("master")
                    .setDirectory(localEiffelRepoPath).call();
        } else {
            // If required repository already exists
            localGitRepo = Git.open(localEiffelRepoPath);

            // Reset to normal if uncommitted changes are present
            localGitRepo.reset().call();

            //Checkout to master before pull the changes
            localGitRepo.checkout().setName(EiffelConstants.MASTER).call();

            // To get the latest changes from remote repository.
            localGitRepo.pull().call();
        }

        //checkout to input branch after changes pulled into local
        localGitRepo.checkout().setName(branch).call();

    } catch (Exception e) {
        LOGGER.info(
                "please check proxy settings if proxy enabled update proxy.properties file to clone behind proxy");
        e.printStackTrace();
    }
}

From source file:com.google.gct.idea.appengine.synchronization.SampleSyncTask.java

License:Apache License

private void updateSampleRepo() {
    Git localGitRepo = getLocalRepo();

    if (localGitRepo == null) {
        // clone repo
        localGitRepo = cloneGithubRepo();
    } else {/*  w w  w.  j a  va2  s  .c o m*/
        // sync repo
        try {
            localGitRepo.pull().call();
        } catch (GitAPIException e) {
            LOG.error("Error syncing local sample repository", e);
        }
    }

    if (localGitRepo != null) {
        localGitRepo.getRepository().close();
    }
}

From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java

License:Open Source License

/**
* Push git changes from remote git repository
* 
* @param git Local git repository/*from w  w  w.java2s.com*/
* @param name Remote Git name
* @param url Remote Git url
* @return pull result
* @throws WsSrvException
*/
public static boolean pullFromRemote(Git git, String name, String url) throws WsSrvException {
    checkRemoteGitConfig(name, url);

    try {
        PullResult pres = git.pull().setRemote(name).call();

        return pres.isSuccessful();
    } catch (GitAPIException e) {
        //-- 250
        throw new WsSrvException(250, e, "Error pull from remote [" + name + "]");
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public boolean updateProject(RepoDetail repodetail, File updateDir) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.updateproject()");
    }/*from  w  w w.j  a  v a  2 s  .  c  o m*/
    com.photon.phresco.framework.impl.util.FrameworkUtil.saveCredential(repodetail, null);
    if (SVN.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("SVN type");
        }
        DAVRepositoryFactory.setup();
        SVNClientManager svnClientManager = getSVNClientManager(repodetail.getUserName(),
                repodetail.getPassword());
        if (debugEnabled) {
            S_LOGGER.debug("update SCM Connection " + repodetail.getRepoUrl());
        }
        //          updateSCMConnection(appInfo, repodetail.getRepoUrl());
        // revision = HEAD_REVISION.equals(revision) ? revision
        // : revisionVal;
        if (debugEnabled) {
            S_LOGGER.debug("updateDir SVN... " + updateDir);
            S_LOGGER.debug("Updating...");
        }
        SVNUpdateClient uc = svnClientManager.getUpdateClient();
        uc.doUpdate(updateDir, SVNRevision.parse(repodetail.getRevision()), SVNDepth.UNKNOWN, true, true);
        if (debugEnabled) {
            S_LOGGER.debug("Updated!");
        }
        return true;
    } else if (GIT.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("GIT type");
        }
        //         updateSCMConnection(appInfo, repodetail.getRepoUrl());
        if (debugEnabled) {
            S_LOGGER.debug("updateDir GIT... " + updateDir);
        }
        //for https and ssh
        additionalAuthentication(repodetail.getPassPhrase());

        UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                repodetail.getUserName(), repodetail.getPassword());
        Git git = Git.open(updateDir); // checkout is the folder with .git
        git.pull().setCredentialsProvider(userCredential).call(); // succeeds
        git.getRepository().close();
        if (debugEnabled) {
            S_LOGGER.debug("Updated!");
        }
        return true;
    } else if (BITKEEPER.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("BITKEEPER type");
        }
        updateFromBitKeeperRepo(repodetail.getRepoUrl(), updateDir.getPath());
    } else if (PERFORCE.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("PERFORCE type");
        }
        String baseDir = updateDir.getAbsolutePath();
        perforceSync(repodetail, baseDir, updateDir.getName(), "update");
        //         updateSCMConnection(appInfo, repodetail.getRepoUrl()+repodetail.getStream());
    } else if (TFS.equals(repodetail.getType())) {
        int responseCode = getProjectFromTFS(repodetail, updateDir.getCanonicalPath());
        if (responseCode == -1) {
            return true;
        }
    }

    return false;
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Pull repo./*from  w  w  w .ja v  a 2  s .  co  m*/
 * 
 * @param localPath
 * @param user
 * @param password
 * @param pm
 * @throws GitError
 */
public static void pull(String localPath, String user, String password, ProgressMonitor pm) throws GitError {
    try {
        Git git = Git.open(new File(localPath));
        PullCommand pull = git.pull();
        pull.setProgressMonitor(pm);
        if ((user != null) && (password != null)) {
            UsernamePasswordCredentialsProvider access = new UsernamePasswordCredentialsProvider(user,
                    password);
            pull.setCredentialsProvider(access);
        }
        pull.call();
        return;
    } catch (DetachedHeadException e) {
        Log.e(TAG, "Detached head", e);
        GittApp.saveErrorTrace(e);
        throw new NoHeadError();
    } catch (InvalidRemoteException e) {
        Log.e(TAG, "InvalidRemote", e);
        GittApp.saveErrorTrace(e);
        throw new NotGitRepoError();
    } catch (TransportException e) {
        String trace = GittApp.saveErrorTrace(e);
        if (trace.indexOf("not authorized") != -1) {
            Log.e(TAG, "Auth", e);
            throw new AuthFailError();
        }
        Log.e(TAG, "Transport", e);
        throw new ConnectionError();
    } catch (GitAPIException e) {
        Log.e(TAG, "GitApi", e);
        GittApp.saveErrorTrace(e);
    } catch (IOException e) {
        Log.e(TAG, "IO", e);
        GittApp.saveErrorTrace(e);
    } catch (JGitInternalException e) {
        Log.e(TAG, "GitInternal", e);
        GittApp.saveErrorTrace(e);
        if (e.getCause() instanceof NotSupportedException) {
            throw new ConnectionError();
        }
    }
    throw new GitError();
}

From source file:com.searchcode.app.jobs.IndexGitRepoJob.java

private RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    try {//from w w  w  .j  a  va 2s.c o m
        Repository localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");

        Git git = new Git(localRepository);
        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}