Example usage for org.eclipse.jgit.api Git lsRemote

List of usage examples for org.eclipse.jgit.api Git lsRemote

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git lsRemote.

Prototype

public LsRemoteCommand lsRemote() 

Source Link

Document

Return a command object to execute a ls-remote command

Usage

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

@SuppressWarnings("restriction")
@Override//  w  ww .j  ava  2  s  .c  o  m
public List<IReviewDescriptor> getReviews(URI uri) throws InvalidReviewRepositoryException {

    List<IReviewDescriptor> changeIds = new LinkedList<>();

    try {
        // connect to the local git repository
        Git git = Git.open(new File(uri));

        try {
            // Assume that origin refers to the remote gerrit repository
            // list all remote refs from origin
            Collection<Ref> remoteRefs = git.lsRemote().setTimeout(60).call();

            Pattern changeRefPattern = Pattern.compile(CHANGE_REF_PATTERN);

            // search for change refs
            for (Ref ref : remoteRefs) {

                Matcher matcher = changeRefPattern.matcher(ref.getName());
                if (matcher.matches()) {
                    String changePk = matcher.group(CHANGE_REF_PATTERN_GROUP_CHANGE_PK);
                    String changeId = "<unknown>";
                    GerritReviewDescriptor reviewDescriptor;
                    try {
                        reviewDescriptor = new GerritReviewDescriptor(Integer.parseInt(changePk), changeId);
                    } catch (NumberFormatException nfe) {
                        // FIXME ignore it or throw an exception?
                        break;
                    }

                    if (!changeIds.contains(reviewDescriptor)) {
                        changeIds.add(reviewDescriptor);

                        /*
                         * the change id is present in all commit messages,
                         * so we extract it from the commit message of the
                         * current ref
                         */
                        FetchResult fetchResult = git.fetch().setRefSpecs(new RefSpec(ref.getName())).call();

                        Ref localRef = fetchResult.getAdvertisedRef(ref.getName());
                        RevWalk revWalk = new RevWalk(git.getRepository());
                        RevCommit commit = revWalk.parseCommit(localRef.getObjectId());
                        String[] paragraphs = commit.getFullMessage().split("\n");
                        String lastParagraph = paragraphs[paragraphs.length - 1];
                        Pattern pattern = Pattern.compile(".*Change-Id: (I[^ \n]*).*");
                        Matcher changeIdMatcher = pattern.matcher(lastParagraph);

                        if (changeIdMatcher.matches()) {
                            changeId = changeIdMatcher.group(1);
                            reviewDescriptor.setChangeId(changeId);
                            ;
                        } else {
                            logger.warn(MessageFormat.format(
                                    "Could not find the change id for Gerrit change with primary key {0}",
                                    changePk));
                        }
                        revWalk.close();
                    }
                }
            }

        } catch (GitAPIException e) {
            throw new RepositoryIOException("Error during loading all remote changes", e);
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    }
    return changeIds;
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws AuthenticationException //from w w  w . j ava  2 s  . co m
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, String password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    log.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", localFolder,
            remoteAddress, username);
    try {
        File gitFolder = new File(localFolder, ".git");
        Repository r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            log.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);

        Git git = new Git(r);

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));

        log.debug("Fetching");
        FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();
        log.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();
        for (Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                log.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            //we need to fetch and (maybe) merge - get onto origin/master.

            log.debug("Fetching from remote");
            String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();
            log.debug("Fetch Result: {}", fetchResult);

            log.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            //Get the files from master that we didn't have in our working folder
            log.debug("Checking out missing files from origin/master");
            for (String missing : git.status().call().getMissing()) {
                log.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    log.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            //just push
            //make sure we have something to push
            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding readme file").setAuthor(username, "42").call();
            }

            log.debug("Pushing repository");
            for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                log.debug("Push Result: {}", pr.getMessages());
            }
        }

        log.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.list.JGitListCommand.java

License:Apache License

@Override
protected ListScmResult executeListCommand(ScmProviderRepository repo, ScmFileSet fileSet, boolean recursive,
        ScmVersion scmVersion) throws ScmException {

    Git git = null;
    try {/*  w ww.  j a  v  a  2  s  .  c om*/
        git = Git.open(fileSet.getBasedir());
        CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git,
                (GitScmProviderRepository) repo);

        List<ScmFile> list = new ArrayList<ScmFile>();
        Collection<Ref> lsResult = git.lsRemote().setCredentialsProvider(credentials).call();
        for (Ref ref : lsResult) {
            getLogger().debug(ref.getObjectId().getName() + "  " + ref.getTarget().getName());
            list.add(new ScmFile(ref.getName(), ScmFileStatus.CHECKED_IN));
        }

        return new ListScmResult("JGit ls-remote", list);
    } catch (Exception e) {
        throw new ScmException("JGit ls-remote failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.remoteinfo.JGitRemoteInfoCommand.java

License:Apache License

@Override
public RemoteInfoScmResult executeRemoteInfoCommand(ScmProviderRepository repository, ScmFileSet fileSet,
        CommandParameters parameters) throws ScmException {

    GitScmProviderRepository repo = (GitScmProviderRepository) repository;
    Git git = null;
    try {/*w  w  w  .j a va 2 s .  co m*/
        git = Git.open(fileSet.getBasedir());
        CredentialsProvider credentials = JGitUtils.getCredentials(repo);

        LsRemoteCommand lsCommand = git.lsRemote().setRemote(repo.getPushUrl())
                .setCredentialsProvider(credentials);

        Map<String, String> tag = new HashMap<String, String>();
        Collection<Ref> allTags = lsCommand.setHeads(false).setTags(true).call();
        for (Ref ref : allTags) {
            tag.put(Repository.shortenRefName(ref.getName()), ref.getObjectId().name());
        }

        Map<String, String> heads = new HashMap<String, String>();
        Collection<Ref> allHeads = lsCommand.setHeads(true).setTags(false).call();
        for (Ref ref : allHeads) {
            heads.put(Repository.shortenRefName(ref.getName()), ref.getObjectId().name());
        }

        return new RemoteInfoScmResult("JGit remoteinfo", heads, tag);
    } catch (Exception e) {
        throw new ScmException("JGit remoteinfo failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

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

License:Open Source License

@RemoteInvocation
public List<Object> getBranches(ServiceInvocationContext context, String repositoryUrl) {
    tlCommand.set((InvokeServiceMethodServerCommand) context.getCommand());
    Repository db = null;/*  w  ww. jav  a  2 s.co m*/
    try {
        URIish uri = new URIish(repositoryUrl.trim());
        db = new FileRepository(new File("/tmp"));

        Git git = new Git(db);
        LsRemoteCommand rc = git.lsRemote();
        rc.setRemote(uri.toString()).setTimeout(30);

        Collection<Ref> remoteRefs = rc.call();
        List<GitRef> branches = new ArrayList<GitRef>();

        Ref idHEAD = null;
        for (Ref r : remoteRefs) {
            if (r.getName().equals(Constants.HEAD)) {
                idHEAD = r;
            }
        }
        Ref head = null;
        boolean headIsMaster = false;
        String masterBranchRef = Constants.R_HEADS + Constants.MASTER;
        for (Ref r : remoteRefs) {
            String n = r.getName();
            if (!n.startsWith(Constants.R_HEADS))
                continue;
            branches.add(new GitRef(n, Repository.shortenRefName(n)));
            if (idHEAD == null || headIsMaster)
                continue;
            if (r.getObjectId().equals(idHEAD.getObjectId())) {
                headIsMaster = masterBranchRef.equals(r.getName());
                if (head == null || headIsMaster)
                    head = r;
            }
        }
        Collections.sort(branches, new Comparator<GitRef>() {
            public int compare(GitRef r1, GitRef r2) {
                return r1.getShortName().compareTo(r2.getShortName());
            }
        });
        if (idHEAD != null && head == null) {
            head = idHEAD;
            branches.add(0, new GitRef(idHEAD.getName(), Repository.shortenRefName(idHEAD.getName())));
        }

        GitRef headRef = head != null ? new GitRef(head.getName(), Repository.shortenRefName(head.getName()))
                : null;
        return Arrays.asList(new Object[] { branches, headRef });
    } catch (JGitInternalException | GitAPIException e) {
        context.getCommunicationChannel()
                .appendOrSendCommand(
                        new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                                GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotListBranches")
                                        + "\n" + e.getCause().getMessage(),
                                DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (IOException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.cloneWizard.branch.cannotCreateTempRepo"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (URISyntaxException e) {
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getReason(), DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (Exception e) {
        if (GitPlugin.getInstance().getUtils().isAuthentificationException(e)) {
            openLoginWindow();
            return null;
        }
        logger.debug(CommonPlugin.getInstance().getMessage("error"), e);
    } finally {
        if (db != null) {
            db.close();
        }
    }
    return null;
}

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

License:Open Source License

@Override
public String getCurrentRevision(VcsRepository repository) throws Exception {
    Git git = new Git(new FileRepository("tmp-ls")); // FIXME
    Collection<Ref> refs = git.lsRemote().setRemote(repository.getUrl()).call();

    String headId = null;//from  w w w .j  a  va  2  s  .  co  m
    for (Ref ref : refs) {
        if ("HEAD".equals(ref.getName())) {
            headId = ref.getObjectId().getName();
        }
    }
    return headId;
}

From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * Link and fetch from remote.// w  w w  .  j av a2 s.c  o m
 *
 * @param remoteAddress the remote address
 * @param username the username
 * @param password the password
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws AuthenticationException the authentication exception
 * @see sh.isaac.api.sync.SyncFiles#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, char[] password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    LOG.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", this.localFolder,
            remoteAddress, username);

    Repository r = null;
    Git git = null;

    try {
        final File gitFolder = new File(this.localFolder, ".git");

        r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            LOG.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);
        git = new Git(r);

        final CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                ((password == null) ? new char[] {} : password));

        LOG.debug("Fetching");

        final FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();

        LOG.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        final Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();

        for (final Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                LOG.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            // we need to fetch and (maybe) merge - get onto origin/master.
            LOG.debug("Fetching from remote");

            final String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();

            LOG.debug("Fetch Result: {}", fetchResult);
            LOG.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            // Get the files from master that we didn't have in our working folder
            LOG.debug("Checking out missing files from origin/master");

            for (final String missing : git.status().call().getMissing()) {
                LOG.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    LOG.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            // just push
            // make sure we have something to push
            for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) {
                LOG.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
            }

            git.commit().setMessage("Adding initial files").setAuthor(username, "42").call();
            LOG.debug("Pushing repository");

            for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                LOG.debug("Push Result: {}", pr.getMessages());
            }
        }

        LOG.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (final TransportException te) {
        if (te.getMessage().contains("Auth fail") || te.getMessage().contains("not authorized")) {
            LOG.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            LOG.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (final GitAPIException e) {
        LOG.error("Unexpected", e);
        throw new IOException("Internal error", e);
    } finally {
        if (git != null) {
            git.close();
        }

        if (r != null) {
            r.close();
        }
    }
}