Example usage for org.eclipse.jgit.api FetchCommand setProgressMonitor

List of usage examples for org.eclipse.jgit.api FetchCommand setProgressMonitor

Introduction

In this page you can find the example usage for org.eclipse.jgit.api FetchCommand setProgressMonitor.

Prototype

public FetchCommand setProgressMonitor(ProgressMonitor monitor) 

Source Link

Document

The progress monitor associated with the fetch operation.

Usage

From source file:com.googlesource.gerrit.plugins.github.git.PullRequestImportJob.java

License:Apache License

private void fetchGitHubPullRequest(Repository gitRepo, GHPullRequest pr)
        throws GitAPIException, InvalidRemoteException, TransportException {
    status.update(Code.SYNC, "Fetching", "Fetching PullRequests from GitHub");

    Git git = Git.wrap(gitRepo);//from www . jav a 2  s.  c o m
    FetchCommand fetch = git.fetch();
    fetch.setRemote(ghRepository.getCloneUrl());
    fetch.setRefSpecs(
            new RefSpec("+refs/pull/" + pr.getNumber() + "/head:refs/remotes/origin/pr/" + pr.getNumber()));
    fetch.setProgressMonitor(this);
    fetch.call();
}

From source file:com.rimerosolutions.ant.git.tasks.FetchTask.java

License:Apache License

@Override
public void doExecute() {
    try {/*from ww w .ja  va 2s .  c om*/
        StoredConfig config = git.getRepository().getConfig();
        List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

        if (remoteConfigs.isEmpty()) {
            URIish uri = new URIish(getUri());

            RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);
            remoteConfig.addURI(uri);
            remoteConfig.addFetchRefSpec(new RefSpec("+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES
                    + Constants.DEFAULT_REMOTE_NAME + "/*"));

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_REMOTE, Constants.DEFAULT_REMOTE_NAME);
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_MERGE, Constants.R_HEADS + Constants.MASTER);

            remoteConfig.update(config);
            config.save();
        }

        List<RefSpec> specs = new ArrayList<RefSpec>(3);

        specs.add(new RefSpec(
                "+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/*"));
        specs.add(new RefSpec("+" + Constants.R_NOTES + "*:" + Constants.R_NOTES + "*"));
        specs.add(new RefSpec("+" + Constants.R_TAGS + "*:" + Constants.R_TAGS + "*"));

        FetchCommand fetchCommand = git.fetch().setDryRun(dryRun).setThin(thinPack).setRemote(getUri())
                .setRefSpecs(specs).setRemoveDeletedRefs(removeDeletedRefs);

        setupCredentials(fetchCommand);

        if (getProgressMonitor() != null) {
            fetchCommand.setProgressMonitor(getProgressMonitor());
        }

        FetchResult fetchResult = fetchCommand.call();

        GitTaskUtils.validateTrackingRefUpdates(FETCH_FAILED_MESSAGE, fetchResult.getTrackingRefUpdates());

        log(fetchResult.getMessages());

    } catch (URISyntaxException e) {
        throw new GitBuildException("Invalid URI syntax: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new GitBuildException("Could not save or get repository configuration: " + e.getMessage(), e);
    } catch (InvalidRemoteException e) {
        throw new GitBuildException("Invalid remote URI: " + e.getMessage(), e);
    } catch (TransportException e) {
        throw new GitBuildException("Communication error: " + e.getMessage(), e);
    } catch (GitAPIException e) {
        throw new GitBuildException("Unexpected exception: " + e.getMessage(), e);
    }
}

From source file:net.erdfelt.android.sdkfido.git.internal.InternalGit.java

License:Apache License

@Override
public void pullRemote() throws GitException {
    try {/*from w  w  w.j a  v a2s  . c o m*/
        Git git = new Git(repo);
        FetchCommand fetch = git.fetch();
        fetch.setCheckFetchedObjects(false);
        fetch.setRemoveDeletedRefs(true);
        List<RefSpec> specs = new ArrayList<RefSpec>();
        fetch.setRefSpecs(specs);
        fetch.setTimeout(5000);
        fetch.setDryRun(false);
        fetch.setRemote(IGit.REMOTE_NAME);
        fetch.setThin(Transport.DEFAULT_FETCH_THIN);
        fetch.setProgressMonitor(getProgressMonitor());

        FetchResult result = fetch.call();
        if (result.getTrackingRefUpdates().isEmpty()) {
            return;
        }

        GitInfo.infoFetchResults(repo, result);
    } catch (Throwable t) {
        throw new GitException(t.getMessage(), t);
    }
}

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Fetch from Remote//from   ww  w  .ja  v a2 s .  c o m
 * @param localGitFolder
 * @param userName
 * @param userPassword
 * @throws IOException
 * @throws GitAPIException
 */
public static FetchResult fetchFromRemote(File localGitFolder, String userName, String userPassword,
        ProgressMonitor monitor) throws IOException, GitAPIException {
    try (Git git = Git.open(localGitFolder)) {
        FetchCommand fetchCommand = git.fetch();
        fetchCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, userPassword));
        fetchCommand.setProgressMonitor(monitor);
        return fetchCommand.call();
    }
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public boolean fetch(ServiceInvocationContext context, List<PathFragment> path, RemoteConfig fetchConfig) {
    tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand());

    ProgressMonitor monitor = ProgressMonitor.create(
            GitPlugin.getInstance().getMessage("git.fetch.monitor.title"), context.getCommunicationChannel());

    try {/*from   ww  w  .j a  v  a 2  s .co m*/
        Object node = GenericTreeStatefulService.getNodeByPathFor(path, null);
        GenericTreeStatefulService service = GenericTreeStatefulService.getServiceFromPathWithRoot(path);
        NodeInfo nodeInfo = service.getVisibleNodes().get(node);
        Repository repository = getRepository(nodeInfo);
        if (repository == null) {
            context.getCommunicationChannel().appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    CommonPlugin.getInstance().getMessage("error"), "Cannot find repository for node " + node,
                    DisplaySimpleMessageClientCommand.ICON_ERROR));
            return false;
        }

        String remote = null;
        if (GitNodeType.NODE_TYPE_REMOTE.equals(nodeInfo.getPathFragment().getType())) {
            remote = ((RemoteNode) node).getRemote();
        }

        GitProgressMonitor gitMonitor = new GitProgressMonitor(monitor);
        FetchCommand command;

        if (remote != null) {
            command = new Git(repository).fetch().setRemote(remote);
        } else {
            List<RefSpec> specs = new ArrayList<RefSpec>();
            for (String refMapping : fetchConfig.getFetchMappings()) {
                specs.add(new RefSpec(refMapping));
            }
            command = new Git(repository).fetch().setRemote(new URIish(fetchConfig.getUri()).toPrivateString())
                    .setRefSpecs(specs);
        }
        command.setProgressMonitor(gitMonitor);
        command.setTagOpt(TagOpt.FETCH_TAGS);

        FetchResult fetchResult = command.call();

        dispatchContentUpdate(node);

        context.getCommunicationChannel()
                .appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.fetch.result"),
                        GitPlugin.getInstance().getUtils().handleFetchResult(fetchResult),
                        DisplaySimpleMessageClientCommand.ICON_INFORMATION));

        return true;
    } catch (Exception e) {
        if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) {
            openLoginWindow();
            return true;
        }
        logger.debug(GitPlugin.getInstance().getMessage("git.fetch.error"), e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

From source file:org.flowerplatform.web.git.operation.internal.PullCommand.java

License:Open Source License

/**
 * Executes the {@code Pull} command with all the options and parameters
 * collected by the setter methods (e.g.
 * {@link #setProgressMonitor(ProgressMonitor)}) of this class. Each
 * instance of this class should only be used for one invocation of the
 * command. Don't call this method twice on an instance.
 *
 * @return the result of the pull/* w w w.  j  av a 2 s. co  m*/
 * @throws WrongRepositoryStateException
 * @throws InvalidConfigurationException
 * @throws DetachedHeadException
 * @throws InvalidRemoteException
 * @throws CanceledException
 * @throws RefNotFoundException
 * @throws NoHeadException
 * @throws org.eclipse.jgit.api.errors.TransportException
 * @throws GitAPIException
 */
@SuppressWarnings("restriction")
public PullResult call() throws GitAPIException, WrongRepositoryStateException, InvalidConfigurationException,
        DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException,
        org.eclipse.jgit.api.errors.TransportException {
    checkCallable();

    monitor.beginTask(JGitText.get().pullTaskName, 2);

    Object[] data = GitPlugin.getInstance().getUtils().getFetchPushUpstreamDataRefSpecAndRemote(repo);

    String fullBranch = (String) data[0];
    String branchName = fullBranch.substring(Constants.R_HEADS.length());

    if (!repo.getRepositoryState().equals(RepositoryState.SAFE))
        throw new WrongRepositoryStateException(MessageFormat.format(JGitText.get().cannotPullOnARepoWithState,
                repo.getRepositoryState().name()));

    // get the configured remote for the currently checked out branch
    // stored in configuration key branch.<branch name>.remote
    Config repoConfig = repo.getConfig();
    String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REMOTE);
    if (remote == null)
        // fall back to default remote
        remote = Constants.DEFAULT_REMOTE_NAME;

    // get the name of the branch in the remote repository
    // stored in configuration key branch.<branch name>.merge
    String remoteBranchName = (String) data[1];

    // determines whether rebase should be used after fetching
    boolean doRebase = (boolean) data[3];

    final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
    String remoteUri;
    FetchResult fetchRes;
    if (isRemote) {
        remoteUri = (String) data[2];

        if (monitor.isCancelled())
            throw new CanceledException(
                    MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

        RefSpec refSpec = new RefSpec();
        refSpec = refSpec.setForceUpdate(true);
        refSpec = refSpec.setSourceDestination(remoteBranchName, fullBranch);

        FetchCommand fetch = new Git(repo).fetch().setRemote(remote).setRefSpecs(refSpec);

        fetch.setProgressMonitor(monitor);
        configure(fetch);

        fetchRes = fetch.call();
    } else {
        // we can skip the fetch altogether
        remoteUri = "local repository";
        fetchRes = null;
    }

    monitor.update(1);

    if (monitor.isCancelled())
        throw new CanceledException(
                MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

    // we check the updates to see which of the updated branches
    // corresponds
    // to the remote branch name
    AnyObjectId commitToMerge;
    if (isRemote) {
        Ref r = null;
        if (fetchRes != null) {
            r = fetchRes.getAdvertisedRef(remoteBranchName);
            if (r == null)
                r = fetchRes.getAdvertisedRef(Constants.R_HEADS + remoteBranchName);
        }
        if (r == null)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().couldNotGetAdvertisedRef, remoteBranchName));
        else
            commitToMerge = r.getObjectId();
    } else {
        try {
            commitToMerge = repo.resolve(remoteBranchName);
            if (commitToMerge == null)
                throw new RefNotFoundException(
                        MessageFormat.format(JGitText.get().refNotResolved, remoteBranchName));
        } catch (IOException e) {
            throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e);
        }
    }

    String upstreamName = "branch \'" + Repository.shortenRefName(remoteBranchName) + "\' of " + remoteUri;

    PullResult result;
    if (doRebase) {
        RebaseCommand rebase = new Git(repo).rebase();
        RebaseResult rebaseRes = rebase.setUpstream(commitToMerge).setUpstreamName(upstreamName)
                .setProgressMonitor(monitor).setOperation(Operation.BEGIN).call();
        result = new PullResult(fetchRes, remote, rebaseRes);
    } else {
        MergeCommand merge = new Git(repo).merge();
        merge.include(upstreamName, commitToMerge);
        MergeResult mergeRes = merge.call();
        monitor.update(1);
        result = new PullResult(fetchRes, remote, mergeRes);
    }
    monitor.endTask();
    return result;
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public Collection<PropertyFileDiff> update(ProjectVersion project, IProgressMonitor monitor)
        throws TeamProviderException {

    SubMonitor subMon = SubMonitor.convert(monitor, 100);
    List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>();
    try {//from  www .  j a  v a2 s .  c om
        Repository repository = createRepository(project);
        Git git = Git.wrap(repository);
        FetchCommand fetchCommand = git.fetch();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            fetchCommand.setRemote(stripUserInfo(uri).toString());
        String refspecString = "refs/heads/{0}:refs/remotes/origin/{0}";
        refspecString = MessageFormat.format(refspecString, project.getName());
        RefSpec spec = new RefSpec(refspecString);
        fetchCommand.setRefSpecs(spec);
        subMon.subTask("Fetching from remote");
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            fetchCommand.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        fetchCommand.setCredentialsProvider(createCredentialsProvider(project.getParent()));
        fetchCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(80)));
        fetchCommand.call();
        ObjectId remoteHead = repository.resolve("refs/remotes/origin/" + project.getName() + "^{tree}");

        DiffCommand diff = git.diff();
        subMon.subTask("Caculating Diff");
        diff.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(20)));
        diff.setOldTree(new FileTreeIterator(repository));
        CanonicalTreeParser p = new CanonicalTreeParser();
        ObjectReader reader = repository.newObjectReader();
        try {
            p.reset(reader, remoteHead);
        } finally {
            reader.release();
        }
        diff.setNewTree(p);
        checkCanceled(subMon);
        List<DiffEntry> diffs = diff.call();
        for (DiffEntry diffEntry : diffs) {
            checkCanceled(subMon);
            updatedFiles.add(convertDiffEntry(diffEntry));
            LOGGER.trace(diffEntry.toString());
        }
        if (!updatedFiles.isEmpty()) {
            checkCanceled(subMon);
            //no more cancel after this point
            ObjectId lastCommitID = repository
                    .resolve("refs/remotes/origin/" + project.getName() + "^{commit}");
            LOGGER.info("Merging remote commit {} to {}/{}",
                    new Object[] { lastCommitID, project.getName(), project.getParent().getName() });
            //TODO: use rebase here?
            if (isRebase(project)) {
                RebaseCommand rebase = git.rebase();
                rebase.setUpstream("refs/remotes/origin/" + project.getName());
                RebaseResult result = rebase.call();
                if (result.getStatus().isSuccessful()) {
                    LOGGER.info("Rebase finished: {}", result.getStatus());
                } else {
                    LOGGER.error("Rebase of {} failed. Attempting abort", project.relativePath());
                    rebase = git.rebase();
                    rebase.setOperation(Operation.ABORT);
                    result = rebase.call();
                    LOGGER.error("Abort finished with {}", result.getStatus());
                }
            } else {
                MergeCommand merge = git.merge();
                merge.include(lastCommitID);
                MergeResult mergeResult = merge.call();

                LOGGER.info("Merge finished: {}", mergeResult.getMergeStatus());
            }
        } else
            LOGGER.info("Update finished successfully. Nothing to merge, already up to date");
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } catch (AmbiguousObjectException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } finally {
        monitor.done();
    }
    return updatedFiles;
}

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

License:Open Source License

@Override
public FetchResult fetch(final Git git, final String remote, final String refSpec, final int timeout,
        final boolean fsck, final boolean dryRun, final boolean thin, final boolean prune)
        throws GitAPIException {
    FetchCommand fetch = git.fetch();
    fetch.setCheckFetchedObjects(fsck);//from   w  w  w.j  a  va2  s  .co  m
    fetch.setRemoveDeletedRefs(prune);
    if (refSpec != null)
        fetch.setRefSpecs(new RefSpec(refSpec));
    if (timeout >= 0)
        fetch.setTimeout(timeout);
    fetch.setDryRun(dryRun);
    fetch.setRemote(remote);
    fetch.setThin(thin);
    fetch.setProgressMonitor(new TextProgressMonitor());

    FetchResult result = fetch.call();
    return result;
}

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

License:Open Source License

public static FetchResult fetch(final Git git, final String remote, final String refSpec, final int timeout,
        final boolean fsck, final boolean dryRun, final boolean thin, final boolean prune)
        throws GitAPIException {
    FetchCommand fetch = git.fetch();
    fetch.setCheckFetchedObjects(fsck);/*from  ww w .  java  2 s.c o  m*/
    fetch.setRemoveDeletedRefs(prune);
    if (refSpec != null)
        fetch.setRefSpecs(new RefSpec(refSpec));
    if (timeout >= 0)
        fetch.setTimeout(timeout);
    fetch.setDryRun(dryRun);
    fetch.setRemote(remote);
    fetch.setThin(thin);
    fetch.setProgressMonitor(new TextProgressMonitor());

    FetchResult result = fetch.call();
    return result;
}

From source file:org.jenkinsci.git.FetchOperation.java

License:Open Source License

public RevCommit call() throws IOException {
    FetchCommand fetch = Git.wrap(gitRepo).fetch();
    fetch.setRemote(repo.getUri());/*from w ww. jav  a  2  s. c o m*/
    fetch.setRefSpecs(new RefSpec(repo.getBranch()));
    if (monitor != null)
        fetch.setProgressMonitor(monitor);
    try {
        fetch.call();
        return CommitUtils.getRef(gitRepo, Constants.FETCH_HEAD);
    } catch (GitException e) {
        throw new IOException(e);
    } catch (JGitInternalException e) {
        throw new IOException(e);
    } catch (InvalidRemoteException e) {
        throw new IOException(e);
    }
}