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

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

Introduction

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

Prototype

public FetchCommand setRemote(String remote) 

Source Link

Document

The remote (uri or name) used for 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 w  w  w .ja v  a 2  s  .co  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.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public boolean fetch(final LocalRepoBean repoBean, final String remoteName) throws GitException {
    String remoteToPull = (remoteName != null) ? remoteName : "origin";

    FetchResult result;// w w w. j  av  a 2 s  . co  m
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        FetchCommand fetchCommand = git.fetch();
        fetchCommand.setRemote(remoteToPull);
        fetchCommand.setRefSpecs(new RefSpec("+refs/heads/*:refs/heads/*"));
        result = fetchCommand.call();
        repository.close();
    } catch (GitAPIException | IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }

    boolean hadUpdates = !result.getTrackingRefUpdates().isEmpty();
    return hadUpdates;
}

From source file:eu.cloud4soa.cli.roo.addon.commands.GitManager.java

License:Apache License

public void fetch() throws GitAPIException {
    FetchCommand fetchCommand = git.fetch();
    fetchCommand.setRemote(repoName);
    fetchCommand.call();/*www  . j av  a  2s  .  c o m*/
}

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

License:Apache License

@Override
public void pullRemote() throws GitException {
    try {/* w  w w. j  a v  a 2s  . 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.ajoberstar.gradle.git.tasks.GitFetch.java

License:Apache License

/**
 * Fetches remote changes into a local Git repository.
 *//*from  ww w.j av a  2s . c o  m*/
@TaskAction
public void fetch() {
    FetchCommand cmd = getGit().fetch();
    TransportAuthUtil.configure(cmd, this);
    cmd.setTagOpt(getTagOpt());
    cmd.setCheckFetchedObjects(getCheckFetchedObjects());
    cmd.setDryRun(getDryRun());
    cmd.setRefSpecs(getRefspecs());
    cmd.setRemote(getRemote());
    cmd.setRemoveDeletedRefs(getRemoveDeletedRefs());
    cmd.setThin(getThin());
    try {
        cmd.call();
    } catch (InvalidRemoteException e) {
        throw new GradleException("Invalid remote specified: " + getRemote(), e);
    } catch (TransportException e) {
        throw new GradleException("Problem with transport.", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem with fetch.", e);
    }
    //TODO add progress monitor to log progress to Gradle status bar
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public void fetch(FetchRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;//from   www.ja v a 2 s .  co m
    try {
        List<RefSpec> fetchRefSpecs;
        List<String> refSpec = request.getRefSpec();
        if (!refSpec.isEmpty()) {
            fetchRefSpecs = new ArrayList<>(refSpec.size());
            for (String refSpecItem : refSpec) {
                RefSpec fetchRefSpec = (refSpecItem.indexOf(':') < 0) //
                        ? new RefSpec(Constants.R_HEADS + refSpecItem + ":") //
                        : new RefSpec(refSpecItem);
                fetchRefSpecs.add(fetchRefSpec);
            }
        } else {
            fetchRefSpecs = Collections.emptyList();
        }

        FetchCommand fetchCommand = getGit().fetch();

        // If this an unknown remote with no refspecs given, put HEAD
        // (otherwise JGit fails)
        if (remoteName != null && refSpec.isEmpty()) {
            boolean found = false;
            List<Remote> configRemotes = remoteList(newDto(RemoteListRequest.class));
            for (Remote configRemote : configRemotes) {
                if (remoteName.equals(configRemote.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                fetchRefSpecs = Collections
                        .singletonList(new RefSpec(Constants.HEAD + ":" + Constants.FETCH_HEAD));
            }
        }

        if (remoteName == null) {
            remoteName = Constants.DEFAULT_REMOTE_NAME;
        }
        fetchCommand.setRemote(remoteName);
        remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
                ConfigConstants.CONFIG_KEY_URL);
        fetchCommand.setRefSpecs(fetchRefSpecs);

        int timeout = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        fetchCommand.setRemoveDeletedRefs(request.isRemoveDeletedRefs());

        executeRemoteCommand(remoteUri, fetchCommand);
    } catch (GitException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().contains("Invalid remote: ")) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else if ("Nothing to fetch.".equals(exception.getMessage())) {
            return;
        } else {
            errorMessage = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public PullResponse pull(PullRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;//from ww  w.j a v a2  s  . co m
    try {
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            throw new GitException(ERROR_PULL_MERGING);
        }
        String fullBranch = repository.getFullBranch();
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
        }

        String branch = fullBranch.substring(Constants.R_HEADS.length());

        StoredConfig config = repository.getConfig();
        if (remoteName == null) {
            remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_REMOTE);
            if (remoteName == null) {
                remoteName = Constants.DEFAULT_REMOTE_NAME;
            }
        }
        remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
                ConfigConstants.CONFIG_KEY_URL);

        String remoteBranch;
        RefSpec fetchRefSpecs = null;
        String refSpec = request.getRefSpec();
        if (refSpec != null) {
            fetchRefSpecs = (refSpec.indexOf(':') < 0) //
                    ? new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) //
                    : new RefSpec(refSpec);
            remoteBranch = fetchRefSpecs.getSource();
        } else {
            remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_MERGE);
        }

        if (remoteBranch == null) {
            remoteBranch = fullBranch;
        }

        FetchCommand fetchCommand = getGit().fetch();
        fetchCommand.setRemote(remoteName);
        if (fetchRefSpecs != null) {
            fetchCommand.setRefSpecs(fetchRefSpecs);
        }
        int timeout = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }

        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand);

        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(String.format(ERROR_PULL_REF_MISSING, remoteBranch));
        }
        org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
        if (mergeResult.getMergeStatus()
                .equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
            return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
        }

        if (mergeResult.getConflicts() != null) {
            StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
            message.append(lineSeparator());
            Map<String, int[][]> allConflicts = mergeResult.getConflicts();
            for (String path : allConflicts.keySet()) {
                message.append(path).append(lineSeparator());
            }
            message.append(ERROR_PULL_AUTO_MERGE_FAILED);
            throw new GitException(message.toString());
        }
    } catch (CheckoutConflictException exception) {
        StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
        message.append(lineSeparator());
        for (String path : exception.getConflictingPaths()) {
            message.append(path).append(lineSeparator());
        }
        message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
        throw new GitException(message.toString(), exception);
    } catch (IOException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else {
            errorMessage = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}

From source file:org.eclipse.orion.server.git.jobs.FetchJob.java

License:Open Source License

private IStatus doFetch() throws IOException, CoreException, URISyntaxException, GitAPIException {
    Repository db = getRepository();//w  w w.  ja  v  a 2 s  . com

    Git git = new Git(db);
    FetchCommand fc = git.fetch();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));

    fc.setCredentialsProvider(credentials);
    fc.setRemote(remote);
    if (branch != null) {
        // refs/heads/{branch}:refs/remotes/{remote}/{branch}
        RefSpec spec = new RefSpec(
                Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
        spec = spec.setForceUpdate(force);
        fc.setRefSpecs(spec);
    }
    FetchResult fetchResult = fc.call();
    return handleFetchResult(fetchResult);
}

From source file:org.eclipse.orion.server.git.servlets.FetchJob.java

License:Open Source License

private IStatus doFetch()
        throws IOException, CoreException, JGitInternalException, InvalidRemoteException, URISyntaxException {
    Repository db = getRepository();/*from   w  ww .  j av  a  2s  .c  om*/
    String branch = getRemoteBranch();

    Git git = new Git(db);
    FetchCommand fc = git.fetch();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));

    fc.setCredentialsProvider(credentials);
    fc.setRemote(remote);
    if (branch != null) {
        // refs/heads/{branch}:refs/remotes/{remote}/{branch}
        RefSpec spec = new RefSpec(
                Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
        spec = spec.setForceUpdate(force);
        fc.setRefSpecs(spec);
    }
    FetchResult fetchResult = fc.call();

    // handle result
    for (TrackingRefUpdate updateRes : fetchResult.getTrackingRefUpdates()) {
        Result res = updateRes.getResult();
        // handle status for given ref
        switch (res) {
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case NEW:
        case FORCED:
        case FAST_FORWARD:
        case RENAMED:
            // do nothing, as these statuses are OK
            break;
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
            // show warning, as only force fetch can finish successfully 
            return new Status(IStatus.WARNING, GitActivator.PI_GIT, res.name());
        default:
            return new Status(IStatus.ERROR, GitActivator.PI_GIT, res.name());
        }
    }
    return Status.OK_STATUS;
}

From source file:org.fedoraproject.eclipse.packager.git.api.ConvertLocalToRemoteCommand.java

License:Open Source License

/**
 * Adds the corresponding remote repository as the default name 'origin' to
 * the existing local repository (uses the JGit API)
 *
 * @param uri/*from  w w w  .  j a  va2  s .  com*/
 * @param monitor
 * @throws LocalProjectConversionFailedException
 */
private void addRemoteRepository(String uri, IProgressMonitor monitor)
        throws LocalProjectConversionFailedException {

    try {
        RemoteConfig config = new RemoteConfig(git.getRepository().getConfig(), "origin"); //$NON-NLS-1$
        config.addURI(new URIish(uri));
        String dst = Constants.R_REMOTES + config.getName();
        RefSpec refSpec = new RefSpec();
        refSpec = refSpec.setForceUpdate(true);
        refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$

        config.addFetchRefSpec(refSpec);
        config.update(git.getRepository().getConfig());
        git.getRepository().getConfig().save();

        // fetch all the remote branches,
        // create corresponding branches locally and merge them
        FetchCommand fetch = git.fetch();
        fetch.setRemote("origin"); //$NON-NLS-1$
        fetch.setTimeout(0);
        fetch.setRefSpecs(refSpec);
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        fetch.call();

    } catch (Exception e) {
        throw new LocalProjectConversionFailedException(e.getCause().getMessage(), e);
    }
}