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:edu.wustl.lookingglass.community.CommunityRepository.java

License:Open Source License

private static boolean hasAtLeastOneReference(Repository repo) {
    for (Ref ref : repo.getAllRefs().values()) {
        if (ref.getObjectId() == null) {
            continue;
        }//from   w  w w  . ja v  a 2  s .  c om
        return true;
    }
    return false;
}

From source file:fr.obeo.ariadne.ide.connector.git.internal.explorer.GitExplorer.java

License:Open Source License

/**
 * Computes the references, branches and tags of the Git repository and map them in the Ariadne
 * repository.//  w ww .ja v a 2s . c  o  m
 * 
 * @param gitRepository
 *            The Git repository
 * @param ariadneRepository
 *            The Ariadne repository
 * @param monitor
 *            The progress monitor
 */
private void computeReferences(Repository gitRepository, fr.obeo.ariadne.model.scm.Repository ariadneRepository,
        IProgressMonitor monitor) {
    monitor.subTask(AriadneGitConnectorMessage.getString("GitExplorer.ComputingReferences")); //$NON-NLS-1$

    Map<String, Ref> allRefs = gitRepository.getAllRefs();
    for (Entry<String, Ref> entry : allRefs.entrySet()) {
        String key = entry.getKey();
        Ref reference = entry.getValue();

        ObjectId linkedObject = null;
        if (reference.isPeeled()) {
            linkedObject = this.getLinkedObject(reference);
        } else {
            if (reference.isSymbolic()) {
                linkedObject = this.getLinkedObject(reference.getLeaf());
            } else {
                linkedObject = this.getLinkedObject(reference);
            }
        }

        RevCommit commit = null;

        Set<RevCommit> keySet = this.commit2ariadneCommit.keySet();
        for (RevCommit revCommit : keySet) {
            if (revCommit.getId().equals(linkedObject)) {
                commit = revCommit;
            }
        }

        if (commit != null) {
            if (gitRepository.getTags().containsKey(key)) {
                // tag
                Tag tag = ScmFactory.eINSTANCE.createTag();
                tag.setCommit(this.commit2ariadneCommit.get(commit));
                tag.setName(reference.getName());
                ariadneRepository.getTags().add(tag);
            } else {
                // branch
                Branch branch = ScmFactory.eINSTANCE.createBranch();
                branch.setCommit(this.commit2ariadneCommit.get(commit));
                branch.setName(reference.getName());
                ariadneRepository.getBranches().add(branch);
            }
        } else {
            // A branch linked to something else than a commit...
        }
        monitor.worked(1);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.CommitLoaderImpl.java

License:Apache License

public void fetch(@NotNull Repository db, @NotNull URIish fetchURI, @NotNull Collection<RefSpec> refspecs,
        @NotNull FetchSettings settings) throws IOException, VcsException {
    File repositoryDir = db.getDirectory();
    assert repositoryDir != null : "Non-local repository";
    Lock rmLock = myRepositoryManager.getRmLock(repositoryDir).readLock();
    rmLock.lock();//from w  ww.j  a v  a 2 s . c  om
    try {
        final long start = System.currentTimeMillis();
        synchronized (myRepositoryManager.getWriteLock(repositoryDir)) {
            final long finish = System.currentTimeMillis();
            Map<String, Ref> oldRefs = new HashMap<String, Ref>(db.getAllRefs());
            PERFORMANCE_LOG.debug("[waitForWriteLock] repository: " + repositoryDir.getAbsolutePath()
                    + ", took " + (finish - start) + "ms");
            myFetchCommand.fetch(db, fetchURI, refspecs, settings);
            Map<String, Ref> newRefs = new HashMap<String, Ref>(db.getAllRefs());
            myMapFullPath.invalidateRevisionsCache(db, oldRefs, newRefs);
        }
    } finally {
        rmLock.unlock();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.FetchCommandImpl.java

License:Apache License

@NotNull
private List<Ref> findLockedRefs(@NotNull Repository db) {
    File refsDir = new File(db.getDirectory(), org.eclipse.jgit.lib.Constants.R_REFS);
    List<String> lockFiles = new ArrayList<>();
    //listFilesRecursively always uses / as a separator, we get valid ref names on all OSes
    FileUtil.listFilesRecursively(refsDir, "refs/", false, Integer.MAX_VALUE,
            f -> f.isDirectory() || f.isFile() && f.getName().endsWith(".lock"), lockFiles);
    Map<String, Ref> allRefs = db.getAllRefs();
    List<Ref> result = new ArrayList<>();
    for (String lock : lockFiles) {
        String refName = lock.substring(0, lock.length() - ".lock".length());
        Ref ref = allRefs.get(refName);
        if (ref != null)
            result.add(ref);// ww  w .ja  va  2  s.c o  m
    }
    return result;
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java

License:Apache License

/**
 * Removes branches of a bare repository which are not present in a remote repository
 */// w  w w  .j a  va  2  s. c  om
private static void pruneRemovedBranches(@NotNull Repository db, @NotNull Transport tn) throws IOException {
    FetchConnection conn = null;
    try {
        conn = tn.openFetch();
        Map<String, Ref> remoteRefMap = conn.getRefsMap();
        for (Map.Entry<String, Ref> e : db.getAllRefs().entrySet()) {
            if (!remoteRefMap.containsKey(e.getKey())) {
                try {
                    RefUpdate refUpdate = db.getRefDatabase().newUpdate(e.getKey(), false);
                    refUpdate.setForceUpdate(true);
                    refUpdate.delete();
                } catch (Exception ex) {
                    LOG.info("Failed to prune removed ref " + e.getKey(), ex);
                    break;
                }
            }
        }
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@TestFor(issues = "TW-46854")
@Test(dataProvider = "mirrors")
public void should_update_remote_tracking_branch_in_case_of_fast_forward_update(boolean useMirrors)
        throws Exception {
    File remoteRepo = myTempFiles.createTempDir();

    copyRepository(dataFile("repo_for_fetch.2"), remoteRepo);
    VcsRootImpl root = vcsRoot().withAgentGitPath(getGitPath()).withFetchUrl(remoteRepo)
            .withUseMirrors(useMirrors).build();
    String buildBranchParam = GitUtils.getGitRootBranchParamName(root);

    //run build in master branch
    AgentRunningBuild build = createRunningBuild(map(buildBranchParam, "refs/heads/master"));
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "d47dda159b27b9a8c4cee4ce98e4435eb5b17168",
            myCheckoutDir, build, false);

    //fast-forward update master to point to the same commit as master
    Repository remote = new RepositoryBuilder().setGitDir(remoteRepo).build();
    RefUpdate refUpdate = remote.updateRef("refs/heads/personal");
    refUpdate.setNewObjectId(ObjectId.fromString("add81050184d3c818560bdd8839f50024c188586"));
    refUpdate.update();/*w w  w  . j a  v  a2  s .  co m*/

    //run build in personal branch
    build = createRunningBuild(map(buildBranchParam, "refs/heads/personal"));
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "add81050184d3c818560bdd8839f50024c188586",
            myCheckoutDir, build, false);

    //fast-forward update personal branch to point to the same commit as master
    refUpdate = remote.updateRef("refs/heads/personal");
    refUpdate.setNewObjectId(ObjectId.fromString("d47dda159b27b9a8c4cee4ce98e4435eb5b17168"));
    refUpdate.update();

    //run build on updated personal branch
    build = createRunningBuild(map(buildBranchParam, "refs/heads/personal"));
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "d47dda159b27b9a8c4cee4ce98e4435eb5b17168",
            myCheckoutDir, build, false);

    //both branch and its remote-tracking branch should be updated
    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    then(r.getAllRefs().get("refs/heads/personal").getObjectId().name())
            .isEqualTo("d47dda159b27b9a8c4cee4ce98e4435eb5b17168");
    then(r.getAllRefs().get("refs/remotes/origin/personal").getObjectId().name())
            .isEqualTo("d47dda159b27b9a8c4cee4ce98e4435eb5b17168");
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@TestFor(issues = "TW-38247")
public void checkout_revision_reachable_from_tag() throws Exception {
    myRoot.addProperty(Constants.BRANCH_NAME, "refs/tags/v1.0");
    String revisionInBuild = "2c7e90053e0f7a5dd25ea2a16ef8909ba71826f6";
    myVcsSupport.updateSources(myRoot, CheckoutRules.DEFAULT, revisionInBuild, myCheckoutDir, myBuild, false);

    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    String workingDirRevision = r.getAllRefs().get("HEAD").getObjectId().name();
    assertEquals("Wrong revision on agent", revisionInBuild, workingDirRevision);
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@TestFor(issues = "TW-23707")
public void do_not_create_remote_branch_unexisting_in_remote_repository() throws Exception {
    myRoot.addProperty(Constants.BRANCH_NAME, "refs/changes/1/1");
    myVcsSupport.updateSources(myRoot, CheckoutRules.DEFAULT, "5711cbfe566b6c92e331f95d4b236483f4532eed",
            myCheckoutDir, myBuild, false);
    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    assertEquals("5711cbfe566b6c92e331f95d4b236483f4532eed", r.getBranch());//checkout a detached commit
    Map<String, Ref> refs = r.getAllRefs();
    assertFalse(refs.containsKey("refs/heads/refs/changes/1/1"));
    assertFalse(refs.containsKey("refs/remotes/origin/changes/1/1"));
}

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

License:Apache License

private static void infoRefs(Repository db) {
    Map<String, Ref> refs = db.getAllRefs();
    System.out.printf("%nAll Refs (%d)%n", refs.size());
    Ref head = refs.get(Constants.HEAD);

    if (head == null) {
        System.out.println(" HEAD ref is dead and/or non-existent?");
        return;//from  w ww .  j  a v a  2s . c o m
    }

    Map<String, Ref> printRefs = new TreeMap<String, Ref>();

    String current = head.getLeaf().getName();
    if (current.equals(Constants.HEAD)) {
        printRefs.put("(no branch)", head);
    }

    for (Ref ref : RefComparator.sort(refs.values())) {
        String name = ref.getName();
        if (name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_REMOTES)) {
            printRefs.put(name, ref);
        }
    }

    int maxLength = 0;
    for (String name : printRefs.keySet()) {
        maxLength = Math.max(maxLength, name.length());
    }

    System.out.printf("Refs (Heads/Remotes) (%d)%n", printRefs.size());
    for (Entry<String, Ref> e : printRefs.entrySet()) {
        Ref ref = e.getValue();
        ObjectId objectId = ref.getObjectId();
        System.out.printf("%c %-" + maxLength + "s %s%n", (current.equals(ref.getName()) ? '*' : ' '),
                e.getKey(), objectId.abbreviate(ABBREV_LEN).name());
    }
}

From source file:net.mobid.codetraq.runnables.ServerTracker.java

License:Open Source License

private RevCommit[] getCommits(int howManyCommits, Repository repo) {
    if (howManyCommits == 0) {
        return null;
    }//from w  ww .  j  a v  a 2 s.co m
    RevWalk rw = new RevWalk(repo);
    for (Ref ref : repo.getAllRefs().values()) {
        try {
            rw.markStart(rw.parseCommit(ref.getObjectId()));
        } catch (Exception notACommit) {
            continue;
        }
    }
    Comparator<RevCommit> commitTimeComparator = new Comparator<RevCommit>() {

        public int compare(RevCommit o1, RevCommit o2) {
            if (o1.getCommitTime() == o2.getCommitTime()) {
                return 0;
            } else if (o1.getCommitTime() > o2.getCommitTime()) {
                return 1;
            }
            return -1;
        }
    };
    ArrayList<RevCommit> commits = new ArrayList<RevCommit>();
    for (RevCommit commit : rw) {
        commits.add(commit);
    }
    Collections.sort(commits, commitTimeComparator);
    Collections.reverse(commits);
    RevCommit[] c = null;
    if (howManyCommits > commits.size()) {
        c = commits.toArray(new RevCommit[howManyCommits]);
    } else {
        c = new RevCommit[howManyCommits];
        for (int i = 0; i < howManyCommits; i++) {
            c[i] = commits.get(i);
        }
    }
    rw.dispose();
    return c;
}