Example usage for org.eclipse.jgit.lib Ref getObjectId

List of usage examples for org.eclipse.jgit.lib Ref getObjectId

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Ref getObjectId.

Prototype

@Nullable
ObjectId getObjectId();

Source Link

Document

Cached value of this ref.

Usage

From source file:RefNode.java

License:Open Source License

public static void createNode(RevWalk walk, Ref ref, boolean recur) throws IOException {
    String key = ref.getName();/*from  www.j  av a  2s  . c o m*/
    ObjectId id = ref.getObjectId();
    Node node;

    if (!nodeMap.containsKey(key)) {
        // create new ref node
        node = new RefNode(key);

        // determine color
        if (key.contains("/heads/")) {
            node.setBackground(new Color(240, 255, 240));
            node.setForeground(new Color(0, 127, 0));
        } else if (key.contains("/tags/")) {
            node.setBackground(new Color(255, 255, 240));
            node.setForeground(new Color(127, 127, 0));
        } else if (key.contains("/remotes/")) {
            node.setBackground(new Color(240, 240, 240));
            node.setForeground(new Color(0, 0, 0));
        } else {
            node.setBackground(new Color(255, 240, 240));
            node.setForeground(new Color(127, 0, 0));
        }

        if (recur) {
            // add parent node
            RevCommit commit = walk.parseCommit(id);
            node.addParent(Node.createNode(walk, commit, recur));
        }
    }
}

From source file:Node.java

License:Open Source License

public static void createNode(RevWalk walk, Ref ref, boolean recur) throws IOException {
    Node.createNode(walk, ref.getObjectId(), recur);
}

From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java

License:Open Source License

private void _run() throws IOException, MinerException, SQLException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(settings.srcLocalPath, ".git")).readEnvironment()
            .findGitDir().build();//from ww  w  . ja  va 2  s  .c o  m

    /*
    Map<String,Ref> refs = repository.getAllRefs();
    for (Map.Entry<String, Ref> ref : refs.entrySet ()) {
       System.out.println (ref.getKey ());
    }
    */

    Ref head = repository.getRef(startRef);
    if (head == null) {
        throw new MinerException("Unknown reference: '" + startRef + "'");
    }

    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(head.getObjectId());
    walk.markStart(commit);
    walk.sort(RevSort.REVERSE);

    // count commit: (fast)
    int commitCount = 0;
    Iterator<RevCommit> iter = walk.iterator();
    while (iter.hasNext()) {
        iter.next();
        commitCount++;
    }

    emitTasksTotal(commitCount);

    // process commits: (slow)
    walk.reset();
    walk.markStart(commit);
    walk.sort(RevSort.REVERSE);

    Map<String, ManagedFile> fileCache = new HashMap<String, ManagedFile>();

    for (RevCommit rev : walk) {
        if (stopped == true) {
            break;
        }

        processCommit(repository, walk, rev, fileCache);
    }

    walk.dispose();
    repository.close();
}

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

License:Open Source License

@SuppressWarnings("restriction")
@Override/* www .j  a va 2s .c om*/
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:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

/**
 * loads all involved models and diagrams for the given patchSet using the
 * given {@link Git} instance from the given git {@link Ref}.
 * /*from w w w . j  a  v a 2s . c  o  m*/
 * @param patchSet
 *            the patch set instance to store the involved models into
 * @param ref
 *            the git ref to the commit which contains the patch set.
 * @param git
 *            the git instance to use
 * @return a list containing the resource sets for the old and the new model
 *         resources.
 * @throws IOException
 */
private List<ResourceSet> loadInvolvedModelsAndDiagrams(PatchSet patchSet, Ref ref, Git git)
        throws IOException {

    String commitHash = ref.getObjectId().name();

    RevWalk revWalk = new RevWalk(git.getRepository());
    RevCommit newCommit = revWalk.parseCommit(ref.getObjectId());
    RevCommit oldCommit = newCommit.getParent(0);
    revWalk.parseHeaders(oldCommit);
    revWalk.close();

    String parentCommitHash = oldCommit.getId().name();

    URI repoURI = git.getRepository().getDirectory().toURI();
    String authority = repoURI.getAuthority();
    String path = repoURI.getPath();
    String repoPath = (authority != null ? authority + "/" : "") + (path != null ? path : "");
    if (repoPath.endsWith("/")) {
        repoPath = repoPath.substring(0, repoPath.length() - 1);
    }

    ResourceSet newResourceSet = createGitAwareResourceSet(commitHash, repoPath,
            Collections.<ResourceSet>emptyList());
    ResourceSet oldModelResourceSet = createGitAwareResourceSet(parentCommitHash, repoPath,
            Collections.<ResourceSet>emptyList());

    for (Patch patch : patchSet.getPatches()) {
        if (patch instanceof ModelPatch || patch instanceof DiagramPatch) {
            org.eclipse.emf.common.util.URI newUri = org.eclipse.emf.common.util.URI
                    .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + commitHash + "/"
                            + patch.getNewPath());

            org.eclipse.emf.common.util.URI oldUri = org.eclipse.emf.common.util.URI
                    .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + parentCommitHash + "/"
                            + patch.getOldPath());

            if (patch.getChangeType() != PatchChangeType.DELETE) {
                // if the patch has been deleted no new resource exists
                Resource newResource = newResourceSet.getResource(newUri, true);
                try {
                    applyResourceContent(newResource, patch, false);
                } catch (IOException e) {
                    throw new IOException(
                            MessageFormat.format("Could not load resource \"{0}\" for patch set {1}",
                                    newUri.toString(), patchSet.getId()),
                            e);
                }
            }

            if (patch.getChangeType() != PatchChangeType.ADD) {
                // if the patch has been added no old resource exists
                Resource oldResource = oldModelResourceSet.getResource(oldUri, true);
                try {
                    applyResourceContent(oldResource, patch, true);
                } catch (IOException e) {
                    throw new IOException(
                            MessageFormat.format("Could not load resource \"{0}\" for patch set {1}",
                                    oldUri.toString(), patchSet.getId()),
                            e);
                }
            }

        }
    }

    List<ResourceSet> resourceSets = new ArrayList<>(2);
    resourceSets.add(oldModelResourceSet);
    resourceSets.add(newResourceSet);
    return resourceSets;
}

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

License:Open Source License

/**
 * loads all patches of from the given list of {@link DiffEntry}s.
 * // w w w  . j a v  a 2  s.co m
 * @param patchSet
 *            the patchSet to add the patches to.
 * @param ref
 *            the ref to the commit of the patch set.
 * @param repository
 *            the git repository instance
 * @throws RepositoryIOException
 */
private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException {

    EList<Patch> patches = patchSet.getPatches();
    Repository repository = git.getRepository();

    try {

        RevWalk revWalk = new RevWalk(repository);
        RevCommit newCommit = revWalk.parseCommit(ref.getObjectId());
        RevCommit oldCommit = newCommit.getParent(0);
        revWalk.parseHeaders(oldCommit);
        ObjectReader objectReader = repository.newObjectReader();
        revWalk.close();

        CanonicalTreeParser newTreeIterator = new CanonicalTreeParser();
        newTreeIterator.reset(objectReader, newCommit.getTree().getId());
        CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser();
        oldTreeIterator.reset(objectReader, oldCommit.getTree().getId());

        List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call();

        for (DiffEntry diff : diffs) {

            String newPath = diff.getNewPath();
            String oldPath = diff.getOldPath();
            Patch patch = null;

            /*
             * only papyrus diagrams are supported for now, so models are in
             * .uml files, diagrams in .notation files
             */

            if (diff.getChangeType() != ChangeType.DELETE) {
                if (newPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (newPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            } else {
                if (oldPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (oldPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            }

            switch (diff.getChangeType()) {
            case ADD:
                patch.setChangeType(PatchChangeType.ADD);
                break;
            case COPY:
                patch.setChangeType(PatchChangeType.COPY);
                break;
            case DELETE:
                patch.setChangeType(PatchChangeType.DELETE);
                break;
            case MODIFY:
                patch.setChangeType(PatchChangeType.MODIFY);
                break;
            case RENAME:
                patch.setChangeType(PatchChangeType.RENAME);
                break;
            }

            patch.setNewPath(newPath);
            patch.setOldPath(oldPath);

            if (diff.getChangeType() != ChangeType.DELETE) {
                ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId());
                patch.setNewContent(objectLoader.getBytes());
            }
            if (diff.getChangeType() != ChangeType.ADD) {
                ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId());
                patch.setOldContent(objectLoader.getBytes());
            }
            patches.add(patch);

        }

    } catch (IOException e) {
        throw new RepositoryIOException(MessageFormat.format(
                "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e);
    } catch (GitAPIException e) {
        throw new RepositoryIOException(
                MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}",
                        patchSet.getId()),
                e);
    }
}

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

License:Open Source License

/**
 * loads the comments for the given {@link ModelReview} from the given
 * repository. The current reviewer should be set for the given model to
 * avoid duplicated user objects representing the same user. The resource
 * set used to load the comments tries to load resources containing
 * referenced EObjects from the given list of model resource sets before
 * creating the resource directly, in order to avoid duplicated model
 * elements. This is necessary as {@link CommentLink}s may refer to objects
 * contained in other resource sets./* w  ww.  j  a  va2  s.  co  m*/
 * 
 * @param repository
 *            the repository to load the comments from.
 * @param modelReview
 *            the {@link ModelReview} to load the comments for.
 * @param modelResourceSets
 *            a list of resource sets to resolve referenced model elements
 *            if they cannot be found in the comments model.
 * @throws RepositoryIOException
 */
private void loadComments(Repository repository, final ModelReview modelReview,
        List<ResourceSet> modelResourceSets) throws RepositoryIOException {

    String commentRefName = getCommentRefName(modelReview);
    String repoPath = repository.getWorkTree().getPath();
    Ref commentRef;

    try {

        commentRef = repository.exactRef(commentRefName);
        String commitHash = commentRef.getObjectId().name();

        /* prepare the resource set and the resource for the comments */
        org.eclipse.emf.common.util.URI commentsUri = org.eclipse.emf.common.util.URI.createURI(
                GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + commitHash + "/" + COMMENTS_FILE_URI);
        ResourceSet resourceSet = createGitAwareResourceSet(commitHash, repoPath, modelResourceSets);
        Resource commentsResource = resourceSet.createResource(commentsUri);

        /* load the comments from the repository */
        commentsResource.load(null);
        final EList<EObject> content = commentsResource.getContents();

        /* add the loaded comments to the given model review */

        TransactionalEditingDomain editingDomain = findTransactionalEditingDomainFor(commentsResource);

        Command addCommentsCommand = new RecordingCommand(editingDomain) {

            @Override
            protected void doExecute() {

                User reviewer = modelReview.getCurrentReviewer();

                for (EObject object : content) {

                    if (object instanceof Comment) {

                        Comment comment = (Comment) object;
                        comment.resolvePatchSet(modelReview);
                        User author = comment.getAuthor();

                        if (isSameUser(reviewer, author)) {
                            // avoid duplicated users
                            comment.setAuthor(reviewer);
                        }

                        modelReview.getComments().add(comment);
                    }
                }
            }

        };

        editingDomain.getCommandStack().execute(addCommentsCommand);

    } catch (IOException e) {
        throw new RepositoryIOException(MessageFormat.format(
                "An IO error occured during loading the comments for the review with id #{0}",
                modelReview.getId()), e);
    }
}

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

License:Open Source License

@Override
public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor)
        throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException {

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

    String repoFileURI = COMMENTS_FILE_URI;

    try {//from www. java 2s .  c  om
        Git git = Git.open(new File(uri));
        Repository repository = git.getRepository();
        ObjectInserter objectInserter = repository.newObjectInserter();

        String commentRefName = getCommentRefName(modelReview);
        Ref commentRef = repository.exactRef(commentRefName);

        DirCache index = DirCache.newInCore();
        DirCacheBuilder dirCacheBuilder = index.builder();

        monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN);

        if (commentRef != null) {

            /*
             * The ref already exists so we have to copy the previous
             * RevTree to keep all already attached files
             */

            RevWalk revWalk = new RevWalk(repository);
            RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId());
            RevTree tree = prevCommit.getTree();

            List<String> ignoredFiles = new ArrayList<>();
            /*
             * add file path of the new file to the ignored file paths, as
             * we don't want any already existing old file in our new tree
             */
            ignoredFiles.add(repoFileURI);
            buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles);

            revWalk.close();
        }

        monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI));

        addCommentsToResource(modelReview, resource);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        resource.save(outputStream, null);

        // insert file as object
        byte[] content = outputStream.toByteArray();
        long length = content.length;
        InputStream inputStream = new ByteArrayInputStream(content);
        ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream);
        inputStream.close();

        // create tree entry
        DirCacheEntry entry = new DirCacheEntry(repoFileURI);
        entry.setFileMode(FileMode.REGULAR_FILE);
        entry.setLastModified(System.currentTimeMillis());
        entry.setLength(length);
        entry.setObjectId(objectId);
        dirCacheBuilder.add(entry);

        dirCacheBuilder.finish();

        // write new tree in database
        ObjectId indexTreeId = index.writeTree(objectInserter);

        monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN);

        // create commit
        CommitBuilder commitBuilder = new CommitBuilder();
        PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview");
        commitBuilder.setCommitter(personIdent);
        commitBuilder.setAuthor(personIdent);
        commitBuilder.setMessage(
                MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName()));

        if (commentRef != null) {
            commitBuilder.setParentId(commentRef.getObjectId());
        }
        commitBuilder.setTreeId(indexTreeId);

        // commit
        ObjectId commitId = objectInserter.insert(commitBuilder);
        objectInserter.flush();

        RefUpdate refUpdate = repository.updateRef(commentRefName);
        refUpdate.setNewObjectId(commitId);
        if (commentRef != null)
            refUpdate.setExpectedOldObjectId(commentRef.getObjectId());
        else
            refUpdate.setExpectedOldObjectId(ObjectId.zeroId());

        /*
         * TODO the result handling below is copied from the CommitCommand
         * class, I don't know if this is really necessary in our case
         */
        Result result = refUpdate.forceUpdate();
        switch (result) {
        case NEW:
        case FORCED:
        case FAST_FORWARD: {
            if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
                /*
                 * Commit was successful. Now delete the files used for
                 * merge commits
                 */
                repository.writeMergeCommitMsg(null);
                repository.writeMergeHeads(null);
            } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeCherryPickHead(null);
            } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeRevertHead(null);
            }
            break;
        }
        case REJECTED:
        case LOCK_FAILURE:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(),
                            refUpdate.getRef(), result));
        default:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            refUpdate.getRef().getName(), commitId.toString(), result)));
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    } finally {
        monitor.done();
    }

}

From source file:bench.MainJgit.java

License:BSD License

/**
 *///from  ww  w .  jav  a  2 s.  c  o m
public static void main(final String[] args) throws Exception {

    final File baseDir = new File(".");

    final File folder = new File(baseDir, "target");

    final File workspace = new File(folder, "workspace");

    FileUtils.delete(workspace, FileUtils.IGNORE_ERRORS | FileUtils.RECURSIVE);

    FileUtils.mkdirs(workspace, true);

    final String remoteURI = "git@github.com:barchart/barchart-jenkins-tester.git";
    final String remoteName = "archon";
    final String remoteBranch = "master";

    final String localBranch = "cascade";

    {
        final Git git = PluginScmGit.doClone(workspace, remoteURI, remoteName);
        final Repository repo = git.getRepository();
        System.out.println("repo " + repo);
    }

    {
        final CheckoutResult result = PluginScmGit.doCheckout(workspace, localBranch, remoteName, remoteBranch);
        System.out.println("checkout " + result.getStatus());
    }

    {
        final CheckoutResult result = PluginScmGit.doCheckout(workspace, localBranch, remoteName, remoteBranch);
        System.out.println("checkout " + result.getStatus());
    }

    {
        final RefSpec fetchSpec = PluginScmGit.refFetch(remoteBranch, remoteName, remoteBranch);

        final FetchResult fetchResult = PluginScmGit.doFetch(workspace, remoteName, fetchSpec);
        System.out.println("fetch satus: " + fetchResult.getAdvertisedRefs());

        final String refHead = PluginScmGit.refHeads(remoteBranch);

        final Ref remoteHead = fetchResult.getAdvertisedRef(refHead);

        final ObjectId commit = remoteHead.getObjectId();

        final MergeResult mergeResult = PluginScmGit.doMerge(workspace, commit);

        final MergeStatus mergeStatus = mergeResult.getMergeStatus();
        System.out.println("merge status: " + mergeStatus);

    }

}

From source file:boa.datagen.scm.GitConnector.java

License:Apache License

@Override
public void getTags(final List<String> names, final List<String> commits) {
    try {// w w w  .  ja va  2 s  .  c  om
        for (final Ref ref : git.tagList().call()) {
            names.add(ref.getName());
            commits.add(ref.getObjectId().getName());
        }
    } catch (final GitAPIException e) {
        if (debug)
            System.err.println("Git Error reading tags: " + e.getMessage());
    }
}