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.openengsb.connector.git.internal.GitServiceImpl.java

License:Apache License

@Override
public List<CommitRef> update() {
    List<CommitRef> commits = new ArrayList<CommitRef>();
    try {//from   w  w  w .j a v a2  s .  co  m
        if (repository == null) {
            prepareWorkspace();
            initRepository();
        }
        Git git = new Git(repository);
        AnyObjectId oldHead = repository.resolve(Constants.HEAD);
        if (oldHead == null) {
            LOGGER.debug("Local repository is empty. Fetching remote repository.");
            FetchResult fetchResult = doRemoteUpdate();
            if (fetchResult.getTrackingRefUpdate(Constants.R_REMOTES + "origin/" + watchBranch) == null) {
                LOGGER.debug("Nothing to fetch from remote repository.");
                return null;
            }
            doCheckout(fetchResult);
        } else {
            LOGGER.debug("Local repository exists. Pulling remote repository.");
            git.pull().call();
        }
        AnyObjectId newHead = repository.resolve(Constants.HEAD);
        if (newHead == null) {
            LOGGER.debug("New HEAD of local repository doesnt exist.");
            return null;
        }
        if (newHead != oldHead) {
            LogCommand logCommand = git.log();
            if (oldHead == null) {
                LOGGER.debug("Retrieving revisions from HEAD [{}] on", newHead.name());
                logCommand.add(newHead);
            } else {
                LOGGER.debug("Retrieving revisions in range [{}, {}]", newHead.name(), oldHead.name());
                logCommand.addRange(oldHead, newHead);
            }
            Iterable<RevCommit> revisions = logCommand.call();
            for (RevCommit revision : revisions) {
                commits.add(new GitCommitRef(revision));
            }
        }
    } catch (Exception e) {
        throw new ScmException(e);
    }
    return commits;
}

From source file:org.ossmeter.platform.vcs.git.GitManager.java

License:Open Source License

protected Git getGit(GitRepository repository) throws Exception {
    String localPath = localBaseDirectory + makeSafe(repository.getUrl()); // FIXME local stora1ge

    Git git;
    File gitDir = new File(localPath);
    if (gitDir.exists()) {
        git = new Git(new FileRepository(localPath + "/.git"));
        git.pull().call();
    } else {// ww  w  .j  a  va  2 s.c  o  m
        git = Git.cloneRepository().setURI(repository.getUrl()).setDirectory(gitDir).call();
    }
    return git;
}

From source file:org.phoenicis.repository.types.GitRepository.java

License:Open Source License

private void cloneOrUpdate() throws RepositoryException {
    final boolean folderExists = this.localFolder.exists();

    // check that the repository folder exists
    if (!folderExists) {
        LOGGER.info("Creating local folder for " + this);

        if (!this.localFolder.mkdirs()) {
            throw new RepositoryException("Couldn't create local folder for " + this);
        }//from w w w.  ja  va2 s.  c o m
    }
    Git gitRepository = null;

    /*
     * if the repository folder previously didn't exist, clone the
     * repository now and checkout the correct branch
     */
    if (!folderExists) {
        LOGGER.info("Cloning " + this);

        try {
            gitRepository = Git.cloneRepository().setURI(this.repositoryUri.toString())
                    .setDirectory(this.localFolder).setBranch(this.branch).call();
        } catch (GitAPIException e) {
            throw new RepositoryException(
                    String.format("Folder '%s' is no git-repository", this.localFolder.getAbsolutePath()), e);
        } finally {
            // close repository to free resources
            if (gitRepository != null) {
                gitRepository.close();
            }
        }
    }
    /*
     * otherwise open the folder and pull the newest updates from the
     * repository
     */
    else {
        // if anything doesn't work here, we still have our local checkout
        // e.g. could be that the git repository cannot be accessed, there is not Internet connection etc.
        // TODO: it might make sense to ensure that our local checkout is not empty / a valid git repository
        try {
            LOGGER.info("Opening " + this);

            gitRepository = Git.open(localFolder);

            LOGGER.info("Pulling new commits from " + this);

            gitRepository.pull().call();
        } catch (Exception e) {
            LOGGER.warn("Could not update {0}. Local checkout will be used.", e);
        } finally {
            // close repository to free resources
            if (gitRepository != null) {
                gitRepository.close();
            }
        }
    }
}

From source file:org.springframework.cloud.config.server.JGitEnvironmentRepository.java

License:Apache License

/**
 * Assumes we are on a tracking branch (should be safe)
 *///from  w w  w.  j a v  a 2s  . c o  m
private void pull(Git git, String label, Ref ref) {
    PullCommand pull = git.pull();
    try {
        if (hasText(getUsername())) {
            setCredentialsProvider(pull);
        }
        pull.call();
    } catch (Exception e) {
        logger.warn("Could not pull remote for " + label + " (current ref=" + ref + "), remote: "
                + git.getRepository().getConfig().getString("remote", "origin", "url"));
    }
}

From source file:org.wandora.application.tools.git.Pull.java

License:Open Source License

@Override
public void execute(Wandora wandora, Context context) {

    try {/*from ww w .jav  a2s .c o  m*/
        Git git = getGit();
        if (git != null) {
            if (isNotEmpty(getGitRemoteUrl())) {
                PullCommand pull = git.pull();
                String user = getUsername();
                if (user == null) {
                    if (pullUI == null) {
                        pullUI = new PullUI();
                    }
                    pullUI.setUsername(getUsername());
                    pullUI.setPassword(getPassword());
                    pullUI.setRemoteUrl(getGitRemoteUrl());

                    pullUI.openInDialog();

                    if (pullUI.wasAccepted()) {
                        setUsername(pullUI.getUsername());
                        setPassword(pullUI.getPassword());
                        // setGitRemoteUrl(pullUI.getRemoteUrl());    

                        // pull.setRemote(pullUI.getRemoteUrl());
                        if (isNotEmpty(getUsername())) {
                            CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
                                    getUsername(), getPassword());
                            pull.setCredentialsProvider(credentialsProvider);
                        }
                    } else {
                        return;
                    }
                }

                setDefaultLogger();
                setLogTitle("Git pull");

                log("Pulling changes from remote repository...");
                PullResult result = pull.call();

                FetchResult fetchResult = result.getFetchResult();
                MergeResult mergeResult = result.getMergeResult();
                MergeStatus mergeStatus = mergeResult.getMergeStatus();

                String fetchResultMessages = fetchResult.getMessages();
                if (isNotEmpty(fetchResultMessages)) {
                    log(fetchResult.getMessages());
                }
                log(mergeStatus.toString());

                if (mergeStatus.equals(MergeStatus.MERGED)) {
                    int a = WandoraOptionPane.showConfirmDialog(wandora, "Reload Wandora project after pull?",
                            "Reload Wandora project after pull?", WandoraOptionPane.YES_NO_OPTION);
                    if (a == WandoraOptionPane.YES_OPTION) {
                        reloadWandoraProject();
                    }
                }
                log("Ready.");
            } else {
                log("Repository has no remote origin and can't be pulled. "
                        + "Initialize repository by cloning remote repository to set the remote origin.");
            }
        } else {
            logAboutMissingGitRepository();
        }
    } catch (GitAPIException gae) {
        log(gae.toString());
    } catch (NoWorkTreeException nwte) {
        log(nwte.toString());
    } catch (Exception e) {
        log(e);
    }
    setState(WAIT);
}

From source file:org.wso2.carbon.appfactory.repository.mgt.git.JGitAgent.java

License:Apache License

/**
 * Re-try the push with using this method.
 *
 * @param remoteRepoUrl remote repository url
 * @param pushBranch branch to push// ww  w.j a va 2 s .c o  m
 * @param repoFile repository directory where .git exists. If not exists will get cloned using {@code
 *                      remoteRepoUrl}
 * @param currentPushTry - Push try count
 * @return success
 * @throws RepositoryMgtException if error while branching
 * @throws GitAPIException if error while merging or pushing
 */
public boolean pushFailed(String remoteRepoUrl, String pushBranch, File repoFile, int currentPushTry)
        throws RepositoryMgtException, GitAPIException {
    log.warn("Re trying " + currentPushTry + " time, for " + repoFile);
    boolean pushed;
    log.warn("Lock obtained for remote repo URL: " + remoteRepoUrl);
    Git gitRepo = getGitRepository(remoteRepoUrl, repoFile);

    gitRepo.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call();
    Iterable<PushResult> pushResults = gitRepo.push().setRemote(remoteRepoUrl)
            .setRefSpecs(new RefSpec("refs/heads/" + pushBranch))
            .setCredentialsProvider(getCredentialsProvider()).call();
    // we need to verify if git push was successful. Here we can check RemoteRefUpdate status is rejected or not.
    pushed = true;
    for (PushResult pushResult : pushResults) {
        if (pushResult.getRemoteUpdates().size() > 0) {
            Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates();
            if (refUpdates != null && refUpdates.size() > 0) {
                for (RemoteRefUpdate refUpdate : refUpdates) {
                    if (refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_OTHER_REASON
                            || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_NODELETE
                            || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD
                            || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED) {
                        pushed = false;
                        log.warn("Failed to push artifacts on repo:" + remoteRepoUrl + " due to "
                                + refUpdate.getStatus() + " Message " + refUpdate.getMessage() + " Application"
                                + repoFile);
                        break;

                    }
                }
            }
        }
    }
    return pushed;

}

From source file:org.z2env.impl.gitcr.GitComponentRepositoryImpl.java

License:Apache License

private void pullRepository(Repository clonedRepo) throws Exception {
    // clone already exists. Pull the deltas
    logger.fine("Pulling deltas from " + getLabel());

    long tStart = System.currentTimeMillis();

    if (hasUriChanged(clonedRepo)) {
        logger.info(// w  ww .  j  a v  a 2 s. com
                "WARNING: URI has changed! Working-clone will be purged and a new clone will be created for "
                        + toString());

        cloneRepository();
        return;
    }

    Git clonedGit = new Git(clonedRepo);

    // get the deltas from the origin repository
    clonedGit.pull().setCredentialsProvider(this.credentials). // set user/password if defined - can be null   
            setTimeout(this.timeout).call();

    logger.info("Pulled deltas within " + (System.currentTimeMillis() - tStart) + "msec from " + toString());

    if (hasBranchChanged(clonedRepo)) {
        logger.info("Branch has changed! Will switch " + toString() + " to " + this.branch);
        GitTools.switchBranch(clonedRepo, this.branch);
    }
}

From source file:org.zanata.sync.jobs.plugin.git.service.impl.GitSyncService.java

License:Open Source License

protected static void checkOutBranch(Git git, String branch) throws GitAPIException, IOException {
    String currentBranch = git.getRepository().getBranch();
    if (currentBranch.equals(branch)) {
        log.info("already on branch: {}. will do a git pull", branch);
        PullResult pullResult = git.pull().call();
        log.debug("pull result: {}", pullResult);
        Preconditions.checkState(pullResult.isSuccessful());
        return;//from www.  j  a  v a 2 s.  c  o  m
    }

    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    /* refs will have name like these:
    refs/heads/master,
    refs/heads/trans,
    refs/heads/zanata,
    refs/remotes/origin/HEAD,
    refs/remotes/origin/master,
    refs/remotes/origin/trans,
    refs/remotes/origin/zanata
            
    where the local branches are: master, trans, zanata
    remote branches are: master, trans, zanata
    */
    Optional<Ref> localBranchRef = Optional.empty();
    Optional<Ref> remoteBranchRef = Optional.empty();
    for (Ref ref : refs) {
        String refName = ref.getName();
        if (refName.equals("refs/heads/" + branch)) {
            localBranchRef = Optional.of(ref);
        }
        if (refName.equals("refs/remotes/origin/" + branch)) {
            remoteBranchRef = Optional.of(ref);
        }
    }

    // if local branch exists and we are now on a different branch,
    // we delete it first then re-checkout
    if (localBranchRef.isPresent()) {
        log.debug("deleting local branch {}", branch);
        git.branchDelete().setBranchNames(branch).call();
    }

    if (remoteBranchRef.isPresent()) {
        // if remote branch exists, we create a new local branch based on it.
        git.checkout().setCreateBranch(true).setForce(true).setName(branch).setStartPoint("origin/" + branch)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    } else {
        // If branch does not exists in remote, create new local branch based on master branch.
        git.checkout().setCreateBranch(true).setForce(true).setName(branch).setStartPoint("origin/master")
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    }
    if (log.isDebugEnabled()) {
        log.debug("current branch is: {}", git.getRepository().getBranch());
    }
}

From source file:pt.up.fe.specs.git.SpecsGit.java

License:Apache License

public static File parseRepositoryUrl(String repositoryPath) {
    String repoName = getRepoName(repositoryPath);

    // Get repo folder
    File eclipseBuildFolder = getRepositoriesFolder();
    File repoFolder = new File(eclipseBuildFolder, repoName);

    // If folder does not exist, or if it exists and is empty, clone repository
    if (!repoFolder.exists() || SpecsIo.isEmptyFolder(repoFolder)) {
        try {//  w w  w  .j av a2  s.c o m
            SpecsLogs.msgInfo("Cloning repo '" + repositoryPath + "' to folder '" + repoFolder + "'");
            Git.cloneRepository().setURI(repositoryPath).setDirectory(repoFolder).call();

            return repoFolder;
        } catch (GitAPIException e) {
            throw new RuntimeException("Could not clone repository '" + repositoryPath + "'", e);
        }
    }

    // Repository already exists, pull

    try {
        SpecsLogs.msgInfo("Pulling repo '" + repositoryPath + "' in folder '" + repoFolder + "'");
        Git gitRepo = Git.open(repoFolder);
        PullCommand pullCmd = gitRepo.pull();
        pullCmd.call();
    } catch (GitAPIException | IOException e) {
        throw new RuntimeException("Could not pull repository '" + repositoryPath + "'", e);
    }

    return repoFolder;
}

From source file:replicatorg.app.ui.panels.UpdateChecker.java

License:Open Source License

private void updateFilaments() {
    final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
    final Git git;
    final Status repoStatus;
    final RemoteAddCommand remoteAddCmd;
    ResetCommand resetCmd;/*w  w  w.j a v a 2 s . c  om*/
    CheckoutCommand checkoutCmd;
    final String currentBranch, newBranch;
    final List<Ref> branchList;
    Repository filamentsRepo;
    boolean branchFoundLocally = false;
    RevCommit stash = null;

    repoBuilder.setMustExist(true);
    repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git"));

    try {
        try {
            Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass());
            filamentsRepo = repoBuilder.build();
        } catch (RepositoryNotFoundException ex) {
            try {
                Base.writeLog("Repository wasn't initialized, initializing it to the given URL: "
                        + FILAMENTS_REPO_URL, this.getClass());
                repoBuilder.setMustExist(false);
                filamentsRepo = repoBuilder.build();
                filamentsRepo.create();
            } catch (IOException ex1) {
                Base.writeLog("IOException while attempting to initialize repository, not updating filaments",
                        this.getClass());
                return;
            }
        }

        currentBranch = filamentsRepo.getBranch();

    } catch (IOException ex) {
        Base.writeLog("IOException while attempting to open repository, not updating filaments",
                this.getClass());
        return;
    }

    git = new Git(filamentsRepo);

    try {
        // it should be only 1, but it shortens the code needed, as the call()
        // method returns an iterable
        for (RevCommit commit : git.log().setMaxCount(1).call()) {
            Base.writeLog("Current commit hash: " + commit, this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog(
                "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update",
                this.getClass());
    }

    try {
        remoteAddCmd = git.remoteAdd();
        remoteAddCmd.setName("origin");
        remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL));
        remoteAddCmd.call();
    } catch (URISyntaxException ex) {
        Base.writeLog("Invalid git filament repo remote URL!", this.getClass());
        return;
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass());
        return;
    }

    try {

        if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) {
            Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH
                    + ", searching for it", this.getClass());
            checkoutCmd = git.checkout();
            checkoutCmd.setName(FILAMENTS_REPO_BRANCH);

            branchList = git.branchList().call();

            for (Ref ref : branchList) {
                if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) {
                    Base.writeLog("Correct branch was found locally", this.getClass());
                    branchFoundLocally = true;
                    break;
                }
            }

            if (branchFoundLocally == false) {
                Base.writeLog(
                        "No correct branch was found locally, attempting to checkout a new branch tracking the remote",
                        this.getClass());
                checkoutCmd.setCreateBranch(true);
                checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
                checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH);
                git.fetch().call();
            }

            RevCommit backup = null;
            if (git.status().call().isClean() == false) {
                git.add().addFilepattern(".").call();
                backup = git.commit().setMessage("local backup of user modifications").call();
            }

            newBranch = checkoutCmd.call().getName();

            if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) {
                Base.writeLog("Unable to change to correct branch, aborting update", this.getClass());
                return;
            } else {
                Base.writeLog("Changed to correct branch, " + newBranch, this.getClass());
            }

            try {
                for (RevCommit commit : git.log().setMaxCount(1).call()) {
                    Base.writeLog("Commit hash after branch change: " + commit, this.getClass());

                }
            } catch (GitAPIException ex) {
                // we don't want all the process to stop just because we couldn't acquire the hash here,
                // hence this catch
                Base.writeLog(
                        "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update",
                        this.getClass());
            }

            if (backup != null) {
                // TODO: restore backup of user modifications
                //git.cherryPick().setNoCommit(true).include(backup).call();
            }
        }

        repoStatus = git.status().call();

        checkoutCmd = git.checkout();
        checkoutCmd.setName(FILAMENTS_REPO_BRANCH);
        checkoutCmd.call();

        git.fetch();
        resetCmd = git.reset();
        resetCmd.setMode(ResetType.HARD);
        resetCmd.call();

        git.pull().call();

        /*
        repoStatus = git.status().call();
        if (repoStatus.hasUncommittedChanges()) {
        Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass());
        stash = git.stashCreate().call();
        git.pull().call();
        git.stashApply().call();        // will apply the last stash made
        git.stashDrop().call();         // remove the last stash made
        } else {
        Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass());
        git.pull().call();
        }
        */

        Base.writeLog("Filament update concluded successfully!", this.getClass());

        try {
            for (RevCommit commit : git.log().setMaxCount(1).call()) {
                Base.writeLog("Commit hash after update process finished: " + commit, this.getClass());

            }
        } catch (GitAPIException ex) {
            // we don't want all the process to stop just because we couldn't acquire the hash here,
            // hence this catch
            Base.writeLog(
                    "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update",
                    this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass());
        try {
            resetCmd = git.reset();
            resetCmd.setMode(ResetType.HARD);
            resetCmd.call();

            if (stash != null) {
                git.stashApply().call();
                git.stashDrop().call();
            }

        } catch (GitAPIException ex1) {
            Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...",
                    this.getClass());
        }
    }

}