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

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

Introduction

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

Prototype

@Nullable
public final Ref exactRef(String name) throws IOException 

Source Link

Document

Get a ref by name.

Usage

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.//  ww  w  . j  ava  2s .  c o 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 {//w  w  w. jav  a  2  s .  co m
        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:com.buildautomation.jgit.api.ShowBranchDiff.java

License:Apache License

private static AbstractTreeIterator prepareTreeParser(Repository repository, String ref)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    Ref head = repository.exactRef(ref);
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(head.getObjectId());
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
        try (ObjectReader oldReader = repository.newObjectReader()) {
            oldTreeParser.reset(oldReader, tree.getId());
        }/*from   w ww.  j  a v a 2s.  c  o m*/

        walk.dispose();

        return oldTreeParser;
    }
}

From source file:com.github.checkstyle.regression.git.DiffParser.java

License:Open Source License

/**
 * Gets a TreeParserPair for the further use.
 * @param repository the repository to parse
 * @param branch     the name of the PR branch
 * @return the TreeParserPair prepared for the further use
 * @throws IOException JGit library exception
 *//*from  ww  w .  j  a v  a  2  s  .  co  m*/
private static TreeParserPair getTreeParserPair(Repository repository, String branch) throws IOException {
    final TreeParserPair returnValue;
    final RevWalk walk = new RevWalk(repository);

    try {
        final RevCommit prCommit = walk
                .parseCommit(repository.exactRef(Constants.R_HEADS + branch).getObjectId());
        final RevCommit masterCommit = walk
                .parseCommit(repository.exactRef(Constants.R_HEADS + "master").getObjectId());
        final RevCommit commonAncestorCommit = getMergeBaseCommit(walk, prCommit, masterCommit);
        walk.dispose();

        returnValue = new TreeParserPair(prepareTreeParser(walk, prCommit),
                prepareTreeParser(walk, commonAncestorCommit));
    } finally {
        walk.close();
    }

    return returnValue;
}

From source file:com.google.gerrit.server.account.AccountsUpdate.java

License:Apache License

public static void deleteUserBranch(Repository repo, PersonIdent refLogIdent, Account.Id accountId)
        throws IOException {
    String refName = RefNames.refsUsers(accountId);
    Ref ref = repo.exactRef(refName);
    if (ref == null) {
        return;//  w  w w.  j  ava 2  s . c  o  m
    }

    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(ref.getObjectId());
    ru.setNewObjectId(ObjectId.zeroId());
    ru.setForceUpdate(true);
    ru.setRefLogIdent(refLogIdent);
    ru.setRefLogMessage("Delete Account", true);
    Result result = ru.delete();
    if (result != Result.FORCED) {
        throw new IOException(String.format("Failed to delete ref %s: %s", refName, result.name()));
    }
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdReader.java

License:Apache License

public static ObjectId readRevision(Repository repo) throws IOException {
    Ref ref = repo.exactRef(RefNames.REFS_EXTERNAL_IDS);
    return ref != null ? ref.getObjectId() : ObjectId.zeroId();
}

From source file:com.google.gerrit.server.git.ChainedReceiveCommands.java

License:Apache License

/**
 * Get the latest value of a ref according to this sequence of commands.
 * <p>//from ww w  .  j  a  v a2 s  .  c  o  m
 * Once the value for a ref is read once, it is cached in this instance, so
 * that multiple callers using this instance for lookups see a single
 * consistent snapshot.
 *
 * @param repo repository to read from, if result is not cached.
 * @param refName name of the ref.
 * @return value of the ref, taking into account commands that have already
 *     been added to this instance. Null if the ref is deleted, matching the
 *     behavior of {@link Repository#exactRef(String)}.
 */
public ObjectId getObjectId(Repository repo, String refName) throws IOException {
    ReceiveCommand cmd = commands.get(refName);
    if (cmd != null) {
        return zeroToNull(cmd.getNewId());
    }
    ObjectId old = oldIds.get(refName);
    if (old != null) {
        return zeroToNull(old);
    }
    Ref ref = repo.exactRef(refName);
    ObjectId id = ref != null ? ref.getObjectId() : null;
    // Cache missing ref as zeroId to match value in commands map.
    oldIds.put(refName, firstNonNull(id, ObjectId.zeroId()));
    return id;
}

From source file:com.google.gerrit.server.notedb.NoteDbChangeState.java

License:Apache License

public boolean isChangeUpToDate(Repository changeRepo) throws IOException {
    Ref ref = changeRepo.exactRef(changeMetaRef(changeId));
    if (ref == null) {
        return changeMetaId.equals(ObjectId.zeroId());
    }/* w w w . java2s .com*/
    return ref.getObjectId().equals(changeMetaId);
}

From source file:com.google.gerrit.server.notedb.NoteDbChangeState.java

License:Apache License

public boolean areDraftsUpToDate(Repository draftsRepo, Account.Id accountId) throws IOException {
    Ref ref = draftsRepo.exactRef(RefNames.refsDraftComments(changeId, accountId));
    if (ref == null) {
        return !draftIds.containsKey(accountId);
    }/*www .  j av  a 2  s .  co m*/
    return ref.getObjectId().equals(draftIds.get(accountId));
}

From source file:com.google.gerrit.server.project.DeleteRef.java

License:Apache License

private void deleteSingleRef(Repository r) throws IOException, ResourceConflictException {
    String ref = refsToDelete.get(0);
    if (prefix != null && !ref.startsWith(prefix)) {
        ref = prefix + ref;//from   w  w w  . ja v a  2s.  com
    }
    RefUpdate.Result result;
    RefUpdate u = r.updateRef(ref);
    u.setExpectedOldObjectId(r.exactRef(ref).getObjectId());
    u.setNewObjectId(ObjectId.zeroId());
    u.setForceUpdate(true);
    refDeletionValidator.validateRefOperation(resource.getName(), identifiedUser.get(), u);
    int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
    for (;;) {
        try {
            result = u.delete();
        } catch (LockFailedException e) {
            result = RefUpdate.Result.LOCK_FAILURE;
        } catch (IOException e) {
            log.error("Cannot delete " + ref, e);
            throw e;
        }
        if (result == RefUpdate.Result.LOCK_FAILURE && --remainingLockFailureCalls > 0) {
            try {
                Thread.sleep(SLEEP_ON_LOCK_FAILURE_MS);
            } catch (InterruptedException ie) {
                // ignore
            }
        } else {
            break;
        }
    }

    switch (result) {
    case NEW:
    case NO_CHANGE:
    case FAST_FORWARD:
    case FORCED:
        referenceUpdated.fire(resource.getNameKey(), u, ReceiveCommand.Type.DELETE,
                identifiedUser.get().getAccount());
        break;

    case REJECTED_CURRENT_BRANCH:
        log.error("Cannot delete " + ref + ": " + result.name());
        throw new ResourceConflictException("cannot delete current branch");

    case IO_FAILURE:
    case LOCK_FAILURE:
    case NOT_ATTEMPTED:
    case REJECTED:
    case RENAMED:
    default:
        log.error("Cannot delete " + ref + ": " + result.name());
        throw new ResourceConflictException("cannot delete: " + result.name());
    }
}