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

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

Introduction

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

Prototype

@Override
public FetchResult call()
        throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException 

Source Link

Document

Execute the fetch command with all the options and parameters collected by the setter methods of this class.

Usage

From source file:com.bb.extensions.plugin.unittests.internal.git.GitWrapper.java

License:Open Source License

/**
 * /*from w  w  w .j a  v  a  2 s . c  om*/
 * @return true if the git repo is up to date.
 */
public boolean isRepoUpToDate() {
    boolean upToDate = true;
    FetchCommand fetchCmd = this.git.fetch();
    try {
        fetchCmd.call();
        BranchTrackingStatus status = BranchTrackingStatus.of(this.git.getRepository(),
                this.git.getRepository().getBranch());
        upToDate = status.getBehindCount() == 0;
    } catch (InvalidRemoteException e) {
        e.printStackTrace();
    } catch (TransportException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return upToDate;
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public void fetch() throws Exception {
    FetchCommand fetchCommand = git.fetch();
    if (credentialsProvider != null)
        fetchCommand.setCredentialsProvider(credentialsProvider);
    try {// w w  w  .  j ava2  s  .  c o m
        fetchCommand.call();
    } catch (JGitInternalException | TransportException ex) {
        // LocalRepo object might be out of sync with actual local repo, so recreate objects for next time
        reconnect();
        throw ex;
    }
}

From source file:com.chungkwong.jgitgui.RemoteTreeItem.java

License:Open Source License

private void gitFetch() {
    ProgressDialog progressDialog = new ProgressDialog(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("FETCH"));
    FetchCommand command = ((Git) getParent().getValue()).fetch()
            .setRemote(((RemoteConfig) getValue()).getName()).setProgressMonitor(progressDialog);
    new Thread(() -> {
        try {//from  w ww. jav  a2 s.c o m
            FetchResult result = command.call();
            ArrayList<CommitTreeItem> commits = new ArrayList<>();
            Platform.runLater(() -> {
                for (Ref ref : result.getAdvertisedRefs())
                    try {
                        commits.add(new CommitTreeItem(((Git) getParent().getValue()).log()
                                .addRange(ref.getObjectId(), ref.getObjectId()).call().iterator().next()));
                    } catch (Exception ex) {
                        Logger.getLogger(RemoteTreeItem.class.getName()).log(Level.SEVERE, null, ex);
                        Util.informUser(ex);
                    }
                getParent().getChildren().filtered(item -> item instanceof LocalTreeItem)
                        .forEach((item) -> item.getChildren().addAll(commits));
            });
        } catch (Exception ex) {
            Logger.getLogger(GitTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Platform.runLater(() -> {
                progressDialog.hide();
                Util.informUser(ex);
            });
        }
    }).start();
}

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

License:Mozilla Public License

@Override
public boolean testConfiguration(Application application, String repo, String branch) throws GitAPIException {
    InitCommand initCommand = new InitCommand();
    File applicationDirectory = DiskUtils.getScratchFile(baseDirectory + application.getId() + "-test");
    initCommand.setDirectory(applicationDirectory);

    Git otherGit = initCommand.call();/*from  w  w  w. j  a  va 2s. co  m*/

    otherGit.getRepository().getConfig().setString("remote", "origin", "url", repo);

    String targetRefSpec = branch == null || branch.isEmpty() ? Constants.R_HEADS + "*:refs/remotes/origin/*"
            : Constants.R_HEADS + branch;

    FetchCommand fetchCommand = otherGit.fetch()
            .setCredentialsProvider(getUnencryptedApplicationCredentials(application)).setDryRun(true)
            .setRefSpecs(new RefSpec(targetRefSpec)).setRemote("origin");

    fetchCommand.call();

    return true;
}

From source file:com.gitblit.manager.GitblitManager.java

License:Apache License

/**
 * Creates a personal fork of the specified repository. The clone is view
 * restricted by default and the owner of the source repository is given
 * access to the clone./*from w  ww  .j a v  a2s .c  o  m*/
 *
 * @param repository
 * @param user
 * @return the repository model of the fork, if successful
 * @throws GitBlitException
 */
@Override
public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException {
    String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(),
            StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
    String fromUrl = MessageFormat.format("file://{0}/{1}",
            repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name);

    // clone the repository
    try {
        Repository canonical = getRepository(repository.name);
        File folder = new File(repositoryManager.getRepositoriesFolder(), cloneName);
        CloneCommand clone = new CloneCommand();
        clone.setBare(true);

        // fetch branches with exclusions
        Collection<Ref> branches = canonical.getRefDatabase().getRefs(Constants.R_HEADS).values();
        List<String> branchesToClone = new ArrayList<String>();
        for (Ref branch : branches) {
            String name = branch.getName();
            if (name.startsWith(Constants.R_TICKET)) {
                // exclude ticket branches
                continue;
            }
            branchesToClone.add(name);
        }
        clone.setBranchesToClone(branchesToClone);
        clone.setURI(fromUrl);
        clone.setDirectory(folder);
        Git git = clone.call();

        // fetch tags
        FetchCommand fetch = git.fetch();
        fetch.setRefSpecs(new RefSpec("+refs/tags/*:refs/tags/*"));
        fetch.call();

        git.getRepository().close();
    } catch (Exception e) {
        throw new GitBlitException(e);
    }

    // create a Gitblit repository model for the clone
    RepositoryModel cloneModel = repository.cloneAs(cloneName);
    // owner has REWIND/RW+ permissions
    cloneModel.addOwner(user.username);

    // ensure initial access restriction of the fork
    // is not lower than the source repository  (issue-495/ticket-167)
    if (repository.accessRestriction.exceeds(cloneModel.accessRestriction)) {
        cloneModel.accessRestriction = repository.accessRestriction;
    }

    repositoryManager.updateRepositoryModel(cloneName, cloneModel, false);

    // add the owner of the source repository to the clone's access list
    if (!ArrayUtils.isEmpty(repository.owners)) {
        for (String owner : repository.owners) {
            UserModel originOwner = userManager.getUserModel(owner);
            if (originOwner != null && !originOwner.canClone(cloneModel)) {
                // origin owner can't yet clone fork, grant explicit clone access
                originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE);
                reviseUser(originOwner.username, originOwner);
            }
        }
    }

    // grant origin's user list clone permission to fork
    List<String> users = repositoryManager.getRepositoryUsers(repository);
    List<UserModel> cloneUsers = new ArrayList<UserModel>();
    for (String name : users) {
        if (!name.equalsIgnoreCase(user.username)) {
            UserModel cloneUser = userManager.getUserModel(name);
            if (cloneUser.canClone(repository) && !cloneUser.canClone(cloneModel)) {
                // origin user can't yet clone fork, grant explicit clone access
                cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE);
            }
            cloneUsers.add(cloneUser);
        }
    }
    userManager.updateUserModels(cloneUsers);

    // grant origin's team list clone permission to fork
    List<String> teams = repositoryManager.getRepositoryTeams(repository);
    List<TeamModel> cloneTeams = new ArrayList<TeamModel>();
    for (String name : teams) {
        TeamModel cloneTeam = userManager.getTeamModel(name);
        if (cloneTeam.canClone(repository) && !cloneTeam.canClone(cloneModel)) {
            // origin team can't yet clone fork, grant explicit clone access
            cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE);
        }
        cloneTeams.add(cloneTeam);
    }
    userManager.updateTeamModels(cloneTeams);

    // add this clone to the cached model
    repositoryManager.addToCachedRepositoryList(cloneModel);

    if (pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager
                .getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onFork(repository, cloneModel);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onFork %s", repository.name), t);
            }
        }
    }
    return cloneModel;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Fetch updates from the remote repository. If refSpecs is unspecifed,
 * remote heads, tags, and notes are retrieved.
 *
 * @param credentialsProvider//  w  w w  . j  a  va2 s  . c o m
 * @param repository
 * @param refSpecs
 * @return FetchResult
 * @throws Exception
 */
public static FetchResult fetchRepository(CredentialsProvider credentialsProvider, Repository repository,
        RefSpec... refSpecs) throws Exception {
    Git git = new Git(repository);
    FetchCommand fetch = git.fetch();
    List<RefSpec> specs = new ArrayList<RefSpec>();
    if (refSpecs == null || refSpecs.length == 0) {
        specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
        specs.add(new RefSpec("+refs/tags/*:refs/tags/*"));
        specs.add(new RefSpec("+refs/notes/*:refs/notes/*"));
    } else {
        specs.addAll(Arrays.asList(refSpecs));
    }
    if (credentialsProvider != null) {
        fetch.setCredentialsProvider(credentialsProvider);
    }
    fetch.setRefSpecs(specs);
    FetchResult fetchRes = fetch.call();
    return fetchRes;
}

From source file:com.google.gerrit.acceptance.GitUtil.java

License:Apache License

public static void fetch(TestRepository<?> testRepo, String spec) throws GitAPIException {
    FetchCommand fetch = testRepo.git().fetch();
    fetch.setRefSpecs(new RefSpec(spec));
    fetch.call();
}

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   ww w.  ja  va2 s.com*/
    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.maiereni.synchronizer.git.utils.GitDownloaderImpl.java

License:Apache License

private List<Change> update(final Git git, final GitProperties properties, final Ref localBranch,
        final Ref tagRef) throws Exception {
    logger.debug("Fetch from remote");
    List<Change> ret = null;
    FetchCommand cmd = git.fetch();
    if (StringUtils.isNotBlank(properties.getUserName()) && StringUtils.isNotBlank(properties.getPassword())) {
        logger.debug("Set credentials");
        cmd.setCredentialsProvider(/*w ww .j a  va2s  .c om*/
                new UsernamePasswordCredentialsProvider(properties.getUserName(), properties.getPassword()));
    }
    if (tagRef != null) {
        RefSpec spec = new RefSpec().setSourceDestination(localBranch.getName(), tagRef.getName());
        List<RefSpec> specs = new ArrayList<RefSpec>();
        specs.add(spec);
        cmd.setRefSpecs(specs);
    }
    FetchResult fr = cmd.call();
    Collection<Ref> refs = fr.getAdvertisedRefs();
    for (Ref ref : refs) {
        if (ref.getName().equals("HEAD")) {
            ret = checkDifferences(git, localBranch, ref);
            logger.debug("Rebase on HEAD");
            RebaseResult rebaseResult = git.rebase().setUpstream(ref.getObjectId()).call();
            if (rebaseResult.getStatus().isSuccessful()) {

            }
        }
    }
    return ret;
}

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

License:Apache License

@Override
public void doExecute() {
    try {//  ww  w  .j a va  2s .  c  o m
        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);
    }
}