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

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

Introduction

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

Prototype

@NonNull
public abstract RefDatabase getRefDatabase();

Source Link

Document

Get the reference database which stores the reference namespace.

Usage

From source file:org.flowerplatform.web.git.history.remote.GitHistoryStatefulService.java

License:Open Source License

private void markStartAllRefs(Repository repo, RevWalk walk, String prefix)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {
    for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(prefix).entrySet()) {
        Ref ref = refEntry.getValue();
        if (ref.isSymbolic())
            continue;
        markStartRef(repo, walk, ref);//from  w ww .  jav a 2  s  .  c om
    }
}

From source file:org.flowerplatform.web.git.history.remote.GitHistoryStatefulService.java

License:Open Source License

private void markStartAdditionalRefs(Repository repo, RevWalk walk) throws IOException {
    List<Ref> additionalRefs = repo.getRefDatabase().getAdditionalRefs();
    for (Ref ref : additionalRefs)
        markStartRef(repo, walk, ref);/*from w w  w.  ja v  a 2 s .  com*/
}

From source file:org.flowerplatform.web.git.history.remote.GitHistoryStatefulService.java

License:Open Source License

private void markUninteresting(Repository repo, RevWalk walk, String prefix)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {
    for (Entry<String, Ref> refEntry : repo.getRefDatabase().getRefs(prefix).entrySet()) {
        Ref ref = refEntry.getValue();
        if (ref.isSymbolic())
            continue;
        Object refTarget = walk.parseAny(ref.getLeaf().getObjectId());
        if (refTarget instanceof RevCommit)
            walk.markUninteresting((RevCommit) refTarget);
    }/*from w w w .j a  v a2 s.  c om*/
}

From source file:org.gitective.core.CommitUtils.java

License:Open Source License

/**
 * Get all the commits that tags in the given repository reference.
 *
 * @param repository/* w  w  w.  j  a va  2s  .co m*/
 * @return non-null but possibly empty collection of commits
 */
public static Collection<RevCommit> getTags(final Repository repository) {
    if (repository == null)
        throw new IllegalArgumentException(Assert.formatNotNull("Repository"));

    final Collection<RevCommit> commits = new HashSet<RevCommit>();
    final RevWalk walk = new RevWalk(repository);
    final RefDatabase refDb = repository.getRefDatabase();
    try {
        getRefCommits(walk, refDb, R_TAGS, commits);
    } catch (IOException e) {
        throw new GitException(e, repository);
    } finally {
        walk.release();
    }
    return commits;
}

From source file:org.gitective.core.CommitUtils.java

License:Open Source License

/**
 * Get all the commits that branches in the given repository reference.
 *
 * @param repository// w w w.j  a  va2 s.c o  m
 * @return non-null but possibly empty collection of commits
 */
public static Collection<RevCommit> getBranches(final Repository repository) {
    if (repository == null)
        throw new IllegalArgumentException(Assert.formatNotNull("Repository"));

    final Collection<RevCommit> commits = new HashSet<RevCommit>();
    final RevWalk walk = new RevWalk(repository);
    final RefDatabase refDb = repository.getRefDatabase();
    try {
        getRefCommits(walk, refDb, R_HEADS, commits);
        getRefCommits(walk, refDb, R_REMOTES, commits);
    } catch (IOException e) {
        throw new GitException(e, repository);
    } finally {
        walk.release();
    }
    return commits;
}

From source file:org.gitective.core.RepositoryUtils.java

License:Open Source License

/**
 * Get the refs with prefix in repository
 *
 * @param repository//from   w w  w  .j a  va  2  s  . c  om
 * @param prefix
 * @return collection of refs
 */
protected static Collection<Ref> getRefs(final Repository repository, final String prefix) {
    try {
        return repository.getRefDatabase().getRefs(prefix).values();
    } catch (IOException e) {
        throw new GitException(e, repository);
    }
}

From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java

License:Educational Community License

/**
 * @param args/*from   ww w.j a  v a 2  s  .com*/
 */
public static void main(String[] args) {

    if (args.length < 4 || args.length > 7) {
        usage();
    }

    File inputFile = new File(args[0]);

    if (!inputFile.exists())
        usage();

    boolean bare = false;

    if (args[2].trim().equals("1")) {
        bare = true;
    }

    String remoteName = args[3].trim();

    String refPrefix = Constants.R_HEADS;

    if (args.length == 5)
        refPrefix = args[4].trim();

    String userName = null;
    String password = null;

    if (args.length == 6)
        userName = args[5].trim();

    if (args.length == 7)
        password = args[6].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false,
                bare);

        Git git = new Git(repo);

        RevWalk rw = new RevWalk(repo);

        ObjectInserter objectInserter = repo.newObjectInserter();

        BufferedReader fileReader = new BufferedReader(new FileReader(inputFile));

        String line = fileReader.readLine();

        int lineNumber = 1;

        BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate();

        List<RefSpec> branchesToDelete = new ArrayList<>();

        while (line != null) {

            if (line.startsWith("#") || line.length() == 0) {
                // skip over comments and blank lines
                line = fileReader.readLine();
                lineNumber++;

                continue;
            }

            String parts[] = line.trim().split(":");

            String branchName = parts[0];

            Ref branchRef = repo.getRef(refPrefix + "/" + branchName);

            if (branchRef == null) {
                log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName);

                line = fileReader.readLine();
                lineNumber++;

                continue;
            }

            String tagName = null;

            if (parts.length > 1)
                tagName = parts[1];

            if (tagName != null) {

                if (tagName.equals("keep")) {
                    log.info("keeping existing branch for {}", branchName);

                    line = fileReader.readLine();
                    lineNumber++;

                    continue;
                }

                if (tagName.equals("tag")) {

                    /*
                     * Shortcut to say make the tag start with the same name as the branch.
                     */
                    tagName = branchName;
                }
                // create a tag

                RevCommit commit = rw.parseCommit(branchRef.getObjectId());

                ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter);

                batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE));

                log.info("converting branch {} into a tag {}", branchName, tagName);

            }

            if (remoteName.equals("local")) {
                batch.addCommand(
                        new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE));
            } else {

                // if the branch is remote then remember its name so we can batch delete after we have the full list.
                branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName));
            }

            line = fileReader.readLine();
            lineNumber++;

        }

        fileReader.close();

        // run the batch update
        batch.execute(rw, new TextProgressMonitor());

        if (!remoteName.equals("local")) {
            // push the tag to the remote right now

            log.info("pushing tags to {}", remoteName);

            PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags()
                    .setProgressMonitor(new TextProgressMonitor());

            if (userName != null)
                pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password));

            Iterable<PushResult> results = pushCommand.call();

            for (PushResult pushResult : results) {

                if (!pushResult.equals(Result.NEW)) {
                    log.warn("failed to push tag " + pushResult.getMessages());
                }
            }

            // delete the branches from the remote

            log.info("pushing branch deletes to remote: {}", remoteName);

            results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete)
                    .setProgressMonitor(new TextProgressMonitor()).call();
        }

        objectInserter.release();

        rw.release();

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:org.kuali.student.git.importer.ConvertBuildTagBranchesToGitTags.java

License:Educational Community License

/**
 * @param args// w ww.  j  a  v a2 s . co  m
 */
public static void main(String[] args) {

    if (args.length < 3 || args.length > 6) {
        System.err.println("USAGE: <git repository> <bare> <ref mode> [<ref prefix> <username> <password>]");
        System.err.println("\t<bare> : 0 (false) or 1 (true)");
        System.err.println("\t<ref mode> : local or name of remote");
        System.err.println("\t<ref prefix> : refs/heads (default) or say refs/remotes/origin (test clone)");
        System.exit(-1);
    }

    boolean bare = false;

    if (args[1].trim().equals("1")) {
        bare = true;
    }

    String remoteName = args[2].trim();

    String refPrefix = Constants.R_HEADS;

    if (args.length == 4)
        refPrefix = args[3].trim();

    String userName = null;
    String password = null;

    if (args.length == 5)
        userName = args[4].trim();

    if (args.length == 6)
        password = args[5].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[0]).getAbsoluteFile(), false,
                bare);

        Git git = new Git(repo);

        ObjectInserter objectInserter = repo.newObjectInserter();

        Collection<Ref> repositoryHeads = repo.getRefDatabase().getRefs(refPrefix).values();

        RevWalk rw = new RevWalk(repo);

        Map<String, ObjectId> tagNameToTagId = new HashMap<>();

        Map<String, Ref> tagNameToRef = new HashMap<>();

        for (Ref ref : repositoryHeads) {

            String branchName = ref.getName().substring(refPrefix.length() + 1);

            if (branchName.contains("tag") && branchName.contains("builds")) {

                String branchParts[] = branchName.split("_");

                int buildsIndex = ArrayUtils.indexOf(branchParts, "builds");

                String moduleName = StringUtils.join(branchParts, "_", buildsIndex + 1, branchParts.length);

                RevCommit commit = rw.parseCommit(ref.getObjectId());

                ObjectId tag = GitRefUtils.insertTag(moduleName, commit, objectInserter);

                tagNameToTagId.put(moduleName, tag);

                tagNameToRef.put(moduleName, ref);

            }

        }

        BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate();

        List<RefSpec> branchesToDelete = new ArrayList<>();

        for (Entry<String, ObjectId> entry : tagNameToTagId.entrySet()) {

            String tagName = entry.getKey();

            // create the reference to the tag object
            batch.addCommand(
                    new ReceiveCommand(null, entry.getValue(), Constants.R_TAGS + tagName, Type.CREATE));

            // delete the original branch object

            Ref branch = tagNameToRef.get(entry.getKey());

            if (remoteName.equals("local")) {

                batch.addCommand(new ReceiveCommand(branch.getObjectId(), null, branch.getName(), Type.DELETE));

            } else {
                String adjustedBranchName = branch.getName().substring(refPrefix.length() + 1);

                branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + adjustedBranchName));
            }

        }

        // create the tags
        batch.execute(rw, new TextProgressMonitor());

        if (!remoteName.equals("local")) {
            // push the tag to the remote right now
            PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags()
                    .setProgressMonitor(new TextProgressMonitor());

            if (userName != null)
                pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password));

            Iterable<PushResult> results = pushCommand.call();

            for (PushResult pushResult : results) {

                if (!pushResult.equals(Result.NEW)) {
                    log.warn("failed to push tag " + pushResult.getMessages());
                }
            }

            // delete the branches from the remote
            results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete)
                    .setProgressMonitor(new TextProgressMonitor()).call();

            log.info("");

        }

        //         Result result = GitRefUtils.createTagReference(repo, moduleName, tag);
        //         
        //         if (!result.equals(Result.NEW)) {
        //            log.warn("failed to create tag {} for branch {}", moduleName, branchName);
        //            continue;
        //         }
        //         
        //         if (deleteMode) {
        //         result = GitRefUtils.deleteRef(repo, ref);
        //   
        //         if (!result.equals(Result.NEW)) {
        //            log.warn("failed to delete branch {}", branchName);
        //            continue;
        //         }

        objectInserter.release();

        rw.release();

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:org.kuali.student.git.importer.ConvertOldBranchesToTagsMain.java

License:Educational Community License

/**
 * @param args//from www. ja  v  a2  s . c o  m
 */
public static void main(String[] args) {

    if (args.length != 3 && args.length != 4) {
        System.err.println("USAGE: <git repository> <mode> <bare> [<ref prefix>]");
        System.err.println("\t<mode> : tag or delete");
        System.err.println("\t<bare> : 0 (false) or 1 (true)");
        System.err.println("\t<ref prefix> : refs/heads (default) or say refs/remotes/origin (test clone)");
        System.exit(-1);
    }

    boolean bare = false;

    if (args[2].trim().equals("1")) {
        bare = true;
    }

    boolean tagMode = false;

    boolean deleteMode = false;

    if (args[1].equals("tag"))
        tagMode = true;
    else if (args[1].equals("delete"))
        deleteMode = true;

    String refPrefix = Constants.R_HEADS;

    if (args.length == 4)
        refPrefix = args[3].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[0]).getAbsoluteFile(), false,
                bare);

        Collection<Ref> repositoryHeads = repo.getRefDatabase().getRefs(refPrefix).values();

        RevWalk rw = new RevWalk(repo);

        Git git = new Git(repo);

        ObjectInserter objectInserter = repo.newObjectInserter();

        List<String> branchesToDelete = new ArrayList<>();

        for (Ref ref : repositoryHeads) {

            if (!ref.getName().contains("@"))
                continue; // we only want those with @ in the name

            if (deleteMode)
                branchesToDelete.add(ref.getName());

            if (!tagMode)
                continue;

            // else tag mode

            String simpleTagName = ref.getName().replaceFirst(refPrefix, "");

            RevCommit commit = rw.parseCommit(ref.getObjectId());

            ObjectId tagId = null;

            // tag this commit
            tagId = GitRefUtils.insertTag(simpleTagName, commit, objectInserter);

            if (tagId != null) {

                // update the tag reference
                // copied from JGit's TagCommand
                Result updateResult = GitRefUtils.createTagReference(repo, simpleTagName, tagId);

                if (updateResult != Result.NEW) {
                    log.warn("problem creating tag reference for " + simpleTagName + " result = "
                            + updateResult);
                }
            }

        }

        if (deleteMode) {

            for (String branch : branchesToDelete) {

                RefUpdate update = repo.updateRef(branch);

                update.setForceUpdate(true);

                Result result = update.delete(rw);

                if (result != Result.FORCED) {

                    log.warn("failed to delete the branch ref = " + branch);
                }

            }
        }

        rw.release();

        objectInserter.flush();
        objectInserter.release();

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:org.kuali.student.git.importer.FixImportRepo.java

License:Educational Community License

/**
 * @param args//from  w ww. j  a va 2  s . co  m
 */
public static void main(final String[] args) {

    if (args.length != 2) {
        log.error("USAGE: <git repository> <reset branches to revision>");
        System.exit(-1);
    }

    try {

        File gitRepository = new File(args[0]).getAbsoluteFile();

        if (!gitRepository.getParentFile().exists())
            throw new FileNotFoundException(args[1] + "path not found");

        final Repository repo = GitRepositoryUtils.buildFileRepository(gitRepository, false);

        String revision = args[1];

        long longRevision = Long.parseLong(revision);

        SvnRevisionMapper mapper = new SvnRevisionMapper(repo);

        mapper.initialize();

        Map<String, Ref> allRefs = new HashMap<String, Ref>();

        Map<String, Ref> existingRefs = repo.getRefDatabase().getRefs(Constants.R_HEADS);

        allRefs.putAll(existingRefs);

        for (SvnRevisionMap entry : mapper.getRevisionHeads(longRevision)) {

            updateRef(repo, entry.getBranchName(), revision, ObjectId.fromString(entry.getCommitId()));

            allRefs.remove(entry.getBranchName().substring(Constants.R_HEADS.length()));
        }

        if (allRefs.size() > 0) {
            // delete all of the left over refs that weren't updated.
            for (Ref ref : allRefs.values()) {

                deleteRef(repo, ref.getName(), revision);

            }
        }

        mapper.truncateTo(longRevision);

        mapper.shutdown();

    } catch (Exception e) {
        log.error("Processing failed", e);
    }

}