Example usage for org.eclipse.jgit.lib Repository getAllRefs

List of usage examples for org.eclipse.jgit.lib Repository getAllRefs

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getAllRefs.

Prototype

@Deprecated
@NonNull
public Map<String, Ref> getAllRefs() 

Source Link

Document

Get mutable map of all known refs, including symrefs like HEAD that may not point to any object yet.

Usage

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

License:Open Source License

@Override
public ModelReview loadReview(URI uri, String id, User currentReviewer, IProgressMonitor monitor)
        throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException {
    /*/*from   w  w w.  ja v  a 2s.  c  om*/
     * Fetch all refs to the patch sets for the particular change and create
     * the model instance from it
     */

    monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN);

    try {
        Git git = Git.open(new File(uri));
        int iId = Integer.parseInt(id);

        // First of all: fetch the patch sets
        // git fetch origin
        // +refs/changes/id%100/<cid>/*:refs/changes/id%100/<cid>/*
        // Refspec of a patchset:
        // +refs/changes/id%100/<cid>/<psId>:refs/changes/id%100/<cid>/<psId>

        monitor.beginTask("Fetching change ref", IProgressMonitor.UNKNOWN);
        git.fetch()
                .setRefSpecs(new RefSpec(MessageFormat.format(
                        "+refs/changes/{0,number,00}/{1}/*:refs/changes/{0,number,00}/{1}/*", iId % 100, iId)))
                .call();

        // create model instance

        ModelReview modelReview = modelReviewFactory.createModelReview();
        modelReview.setId(id);
        modelReview.setRepositoryURI(uri.toString());
        modelReview.setCurrentReviewer(currentReviewer);
        EList<PatchSet> patchSets = modelReview.getPatchSets();

        Repository repository = git.getRepository();
        Map<String, Ref> allRefs = repository.getAllRefs();
        Pattern changeRefPattern = Pattern.compile(CHANGE_REF_PATTERN);

        monitor.beginTask("Loading Patch Sets", allRefs.size());

        List<ResourceSet> resourceSets = new LinkedList<>();

        for (Entry<String, Ref> refEntry : allRefs.entrySet()) {
            Matcher matcher = changeRefPattern.matcher(refEntry.getValue().getName());
            if (matcher.matches() && matcher.group(CHANGE_REF_PATTERN_GROUP_CHANGE_PK).equals(id)) {

                PatchSet patchSet = modelReviewFactory.createPatchSet();
                patchSets.add(patchSet);
                patchSet.setId(matcher.group(CHANGE_REF_PATTERN_GROUP_PATCH_SET_ID));

                monitor.subTask("Loading Patch Set #" + patchSet.getId());

                // load patched files
                loadPatches(patchSet, refEntry.getValue(), git);

                // load involved models
                resourceSets.addAll(loadInvolvedModelsAndDiagrams(patchSet, refEntry.getValue(), git));

                // compare the involved models
                patchSet.setModelComparison(compareModels(patchSet));

                // compare the involved diagrams
                patchSet.setDiagramComparison(compareDiagrams(patchSet));
            }
            monitor.worked(1);
        }

        monitor.beginTask("Sorting Patch Sets", IProgressMonitor.UNKNOWN);

        /*
         * sort by their identifiers, numeric identifiers before string
         * identifiers (gerrit currently has only numeric patch set
         * identifiers, but to be on the save side also consider non-numeric
         * identifiers )
         */
        ECollections.sort(patchSets, new Comparator<PatchSet>() {

            @Override
            public int compare(PatchSet o1, PatchSet o2) {
                String psId1 = o1.getId();
                String psId2 = o2.getId();
                Integer iPsId1 = null;
                Integer iPsId2 = null;
                try {
                    iPsId1 = Integer.valueOf(psId1);
                } catch (NumberFormatException nfe) {
                }
                try {
                    iPsId2 = Integer.valueOf(psId2);
                } catch (NumberFormatException nfe) {
                }

                if (iPsId1 != null && iPsId2 != null) {
                    // both numeric ids
                    return iPsId1.compareTo(iPsId2);
                } else if (iPsId1 != null && iPsId2 == null) {
                    // only one is numeric, the numeric id is always less
                    // than the string id
                    return -1;
                } else if (iPsId1 == null && iPsId2 != null) {
                    // only one is numeric, the numeric id is always less
                    // than the string id
                    return 1;
                }

                // fallback to string sort
                return psId1.compareTo(psId2);
            }
        });

        monitor.beginTask("Loading Comments", IProgressMonitor.UNKNOWN);

        loadComments(repository, modelReview, resourceSets);

        monitor.done();

        return modelReview;

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    } catch (NumberFormatException e) {
        throw new InvalidReviewException(MessageFormat.format("Invalid review id: {0}", id));
    } catch (GitAPIException e) {
        throw new RepositoryIOException("Error occured during reading from the git repository", e);
    }
}

From source file:ch.uzh.ifi.seal.permo.history.git.core.model.jgit.util.JGitUtil.java

License:Apache License

/**
 * Returns a list of all branches of a given remote references.
 * /*from  w  ww .java  2s . com*/
 * @param repository
 *          the repository
 * @param remoteRef
 *          the remote reference (e.g. 'refs/remotes/origin')
 * @return the list of all branches of the given remote reference.
 */
public static List<String> getBranchesOfRemote(final Repository repository, final String remoteRef) {
    final List<String> remoteBranches = Lists.newArrayList();
    for (final Entry<String, Ref> remoteBranch : repository.getAllRefs().entrySet()) {
        if (remoteBranch.getKey().startsWith(remoteRef)) {
            remoteBranches.add(remoteBranch.getKey());
        }
    }
    return remoteBranches;
}

From source file:com.google.gerrit.acceptance.git.RefAdvertisementIT.java

License:Apache License

private void assertRefs(Repository repo, VisibleRefFilter filter, boolean disableDb, String... expectedWithMeta)
        throws Exception {
    List<String> expected = new ArrayList<>(expectedWithMeta.length);
    for (String r : expectedWithMeta) {
        if (notesMigration.commitChangeWrites() || !r.endsWith(RefNames.META_SUFFIX)) {
            expected.add(r);// w  ww .  jav a2 s  .  c o  m
        }
    }

    AcceptanceTestRequestScope.Context ctx = null;
    if (disableDb) {
        ctx = disableDb();
    }
    try {
        Map<String, Ref> all = repo.getAllRefs();
        assertThat(filter.filter(all, false).keySet()).containsExactlyElementsIn(expected);
    } finally {
        if (disableDb) {
            enableDb(ctx);
        }
    }
}

From source file:com.google.gerrit.httpd.rpc.project.AddBranch.java

License:Apache License

private RevWalk verifyConnected(final Repository repo, final ObjectId revid) throws InvalidRevisionException {
    try {//ww w. j  a  v  a 2s .c  o m
        final ObjectWalk rw = new ObjectWalk(repo);
        try {
            rw.markStart(rw.parseCommit(revid));
        } catch (IncorrectObjectTypeException err) {
            throw new InvalidRevisionException();
        }
        for (final Ref r : repo.getAllRefs().values()) {
            try {
                rw.markUninteresting(rw.parseAny(r.getObjectId()));
            } catch (MissingObjectException err) {
                continue;
            }
        }
        rw.checkConnectivity();
        return rw;
    } catch (IncorrectObjectTypeException err) {
        throw new InvalidRevisionException();
    } catch (MissingObjectException err) {
        throw new InvalidRevisionException();
    } catch (IOException err) {
        log.error("Repository \"" + repo.getDirectory() + "\" may be corrupt; suggest running git fsck", err);
        throw new InvalidRevisionException();
    }
}

From source file:com.google.gerrit.httpd.rpc.project.ListBranches.java

License:Apache License

@Override
public ListBranchesResult call() throws NoSuchProjectException {
    final ProjectControl pctl = projectControlFactory.validateFor( //
            projectName, //
            ProjectControl.OWNER | ProjectControl.VISIBLE);

    final List<Branch> branches = new ArrayList<Branch>();
    Branch headBranch = null;/*www  . ja v  a  2 s . c o  m*/
    final Set<String> targets = new HashSet<String>();

    final Repository db;
    try {
        db = repoManager.openRepository(projectName);
    } catch (RepositoryNotFoundException noGitRepository) {
        return new ListBranchesResult(branches, false, true);
    }
    try {
        final Map<String, Ref> all = db.getAllRefs();

        if (!all.containsKey(Constants.HEAD)) {
            // The branch pointed to by HEAD doesn't exist yet, so getAllRefs
            // filtered it out. If we ask for it individually we can find the
            // underlying target and put it into the map anyway.
            //
            try {
                Ref head = db.getRef(Constants.HEAD);
                if (head != null) {
                    all.put(Constants.HEAD, head);
                }
            } catch (IOException e) {
                // Ignore the failure reading HEAD.
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                targets.add(ref.getTarget().getName());
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                // A symbolic reference to another branch, instead of
                // showing the resolved value, show the name it references.
                //
                String target = ref.getTarget().getName();
                RefControl targetRefControl = pctl.controlForRef(target);
                if (!targetRefControl.isVisible()) {
                    continue;
                }
                if (target.startsWith(Constants.R_HEADS)) {
                    target = target.substring(Constants.R_HEADS.length());
                }

                Branch b = createBranch(ref.getName());
                b.setRevision(new RevId(target));

                if (Constants.HEAD.equals(ref.getName())) {
                    b.setCanDelete(false);
                    headBranch = b;
                } else {
                    b.setCanDelete(targetRefControl.canDelete());
                    branches.add(b);
                }
                continue;
            }

            RefControl refControl = pctl.controlForRef(ref.getName());

            if (ref.getName().startsWith(Constants.R_HEADS) && refControl.isVisible()) {
                final Branch b = createBranch(ref.getName());
                if (ref.getObjectId() != null) {
                    b.setRevision(new RevId(ref.getObjectId().name()));
                }

                b.setCanDelete(!targets.contains(ref.getName()) && refControl.canDelete());

                branches.add(b);
            }
        }
    } finally {
        db.close();
    }
    Collections.sort(branches, new Comparator<Branch>() {
        @Override
        public int compare(final Branch a, final Branch b) {
            return a.getName().compareTo(b.getName());
        }
    });
    if (headBranch != null) {
        branches.add(0, headBranch);
    }
    return new ListBranchesResult(branches, pctl.canAddRefs(), false);
}

From source file:com.google.gerrit.server.index.ChangeBatchIndexer.java

License:Apache License

private Callable<Void> reindexProject(final ChangeIndexer indexer, final Project.NameKey project,
        final Task done, final Task failed, final PrintWriter verboseWriter) {
    return new Callable<Void>() {
        @Override//from  w ww.j ava  2 s  .c o m
        public Void call() throws Exception {
            Multimap<ObjectId, ChangeData> byId = ArrayListMultimap.create();
            ReviewDb db = schemaFactory.open();
            try {
                Repository repo = repoManager.openRepository(project);
                try {
                    Map<String, Ref> refs = repo.getAllRefs();
                    for (Change c : db.changes().byProject(project)) {
                        Ref r = refs.get(c.currentPatchSetId().toRefName());
                        if (r != null) {
                            byId.put(r.getObjectId(), new ChangeData(c));
                        }
                    }
                    new ProjectIndexer(indexer, byId, repo, done, failed, verboseWriter).call();
                } finally {
                    repo.close();
                    // TODO(dborowitz): Opening all repositories in a live server may be
                    // wasteful; see if we can determine which ones it is safe to close
                    // with RepositoryCache.close(repo).
                }
            } finally {
                db.close();
            }
            return null;
        }
    };
}

From source file:com.google.gerrit.server.schema.Schema_56.java

License:Apache License

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) {
    for (Project.NameKey name : mgr.list()) {
        Repository git;
        try {//from  w  w w  .  j av  a 2 s. c  om
            git = mgr.openRepository(name);
        } catch (RepositoryNotFoundException e) {
            ui.message("warning: Cannot open " + name.get());
            continue;
        }
        try {
            Map<String, Ref> all = git.getAllRefs();
            if (all.keySet().equals(keysOne) || all.keySet().equals(keysTwo)) {
                try {
                    RefUpdate update = git.updateRef(Constants.HEAD);
                    update.disableRefLog();
                    update.link(GitRepositoryManager.REF_CONFIG);
                } catch (IOException err) {
                    ui.message("warning: " + name.get() + ": Cannot update HEAD to "
                            + GitRepositoryManager.REF_CONFIG + ": " + err.getMessage());
                }
            }
        } finally {
            git.close();
        }
    }
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public Path bundle(final LocalRepoBean repoBean) throws GitException {
    OutputStream outputStream = null;
    try {//  www.  ja v a2s .c  o m
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        BundleWriter bundleWriter = new BundleWriter(repository);
        String fileName = StringUtil.cleanStringForFilePath(repoBean.getProjectKey() + "_" + repoBean.getSlug())
                + ".bundle";
        Path outputPath = Paths.get(PropertyUtil.getTempDir(), fileName);
        outputStream = Files.newOutputStream(outputPath);

        Map<String, Ref> refMap = repository.getAllRefs();
        for (Ref ref : refMap.values()) {
            bundleWriter.include(ref);
        }

        bundleWriter.writeBundle(NullProgressMonitor.INSTANCE, outputStream);
        outputStream.close();
        repository.close();
        return outputPath;
    } catch (IOException e) {
        throw new GitException(e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ioe) {
                LOGGER.error(ioe);
            }
        }
    }
}

From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java

License:Open Source License

private void visitAllCommitsAfter(Repository repository, Date maxDate, CommitVisitor visitor,
        Set<ObjectId> visited) {
    try {//from   w w  w  .  j a v a  2  s.  c om

        for (Entry<String, Ref> entry : repository.getAllRefs().entrySet()) {
            if (entry.getValue().getName().startsWith(Constants.R_HEADS)) {
                RevWalk revWal = new RevWalk(repository);
                revWal.markStart(revWal.parseCommit(entry.getValue().getObjectId()));

                int commitsPastDate = 0;
                for (RevCommit revCommit : revWal) {
                    if (revCommit.getCommitterIdent().getWhen().getTime() < maxDate.getTime()) {
                        commitsPastDate++;
                    } else {
                        commitsPastDate = 0;
                        if (visited.add(revCommit)) {
                            visitor.visit(revCommit);
                        } else {
                            break;
                        }
                    }
                    if (commitsPastDate > 5) {
                        break;
                    }

                }
                revWal.dispose();

            }
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java

License:Open Source License

private List<Ref> getRefsToAdd(Repository repository) {
    List<Ref> result = new ArrayList<Ref>();
    Ref master = null;/* www  .  j  a v  a2s.  co m*/
    for (Entry<String, Ref> entry : repository.getAllRefs().entrySet()) {
        if (entry.getValue().getName().equals(Constants.R_HEADS + Constants.MASTER)) {
            master = entry.getValue();
        } else if (entry.getValue().getName().startsWith(Constants.R_HEADS)) {
            result.add(entry.getValue());
        }
    }
    if (master != null) {
        result.add(0, master);
    }
    return result;
}