Example usage for org.eclipse.jgit.lib ObjectId name

List of usage examples for org.eclipse.jgit.lib ObjectId name

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId name.

Prototype

public final String name() 

Source Link

Document

name.

Usage

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

License:Apache License

private static ExternalId parse(ExternalId.Key key, RevWalk rw, ObjectId rev)
        throws IOException, ConfigInvalidException {
    NoteMap noteMap = readNoteMap(rw, rev);
    ObjectId noteId = key.sha1();
    if (!noteMap.contains(noteId)) {
        return null;
    }/*from w w  w .j  a va 2s  . c o m*/

    byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
    return ExternalId.parse(noteId.name(), raw);
}

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

License:Apache License

/**
 * Removes an external ID from the note map.
 *
 * @throws IllegalStateException is thrown if there is an existing external ID that has the same
 *     key, but otherwise doesn't match the specified external ID.
 *//*from  ww w .j ava  2s . c  o  m*/
public static void remove(RevWalk rw, NoteMap noteMap, ExternalId extId)
        throws IOException, ConfigInvalidException {
    ObjectId noteId = extId.key().sha1();
    if (!noteMap.contains(noteId)) {
        return;
    }

    byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
    ExternalId actualExtId = ExternalId.parse(noteId.name(), raw);
    checkState(extId.equals(actualExtId),
            "external id %s should be removed, but it's not matching the actual external id %s",
            extId.toString(), actualExtId.toString());
    noteMap.remove(noteId);
}

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

License:Apache License

/**
 * Removes an external ID from the note map by external ID key.
 *
 * @throws IllegalStateException is thrown if an expected account ID is provided and an external
 *     ID with the specified key exists, but belongs to another account.
 *///from  w w w . ja v a 2 s. c  om
private static void remove(RevWalk rw, NoteMap noteMap, ExternalId.Key extIdKey, Account.Id expectedAccountId)
        throws IOException, ConfigInvalidException {
    ObjectId noteId = extIdKey.sha1();
    if (!noteMap.contains(noteId)) {
        return;
    }

    byte[] raw = rw.getObjectReader().open(noteMap.get(noteId), OBJ_BLOB).getCachedBytes(MAX_NOTE_SZ);
    ExternalId extId = ExternalId.parse(noteId.name(), raw);
    if (expectedAccountId != null) {
        checkState(expectedAccountId.equals(extId.accountId()),
                "external id %s should be removed for account %s," + " but external id belongs to account %s",
                extIdKey.get(), expectedAccountId.get(), extId.accountId().get());
    }
    noteMap.remove(noteId);
}

From source file:com.google.gerrit.server.change.ChangeKindCacheImpl.java

License:Apache License

@Override
public ChangeKind getChangeKind(ProjectState project, Repository repo, ObjectId prior, ObjectId next) {
    try {//from ww  w . ja  va  2  s  .  c  o  m
        Key key = new Key(prior, next, useRecursiveMerge);
        return cache.get(key, new Loader(key, repo));
    } catch (ExecutionException e) {
        log.warn("Cannot check trivial rebase of new patch set " + next.name() + " in "
                + project.getProject().getName(), e);
        return ChangeKind.REWORK;
    }
}

From source file:com.google.gerrit.server.change.CherryPickChange.java

License:Apache License

public Change.Id cherryPick(Change change, PatchSet patch, final String message, final String ref,
        final RefControl refControl) throws NoSuchChangeException, OrmException, MissingObjectException,
        IncorrectObjectTypeException, IOException, InvalidChangeOperationException, MergeException {

    if (Strings.isNullOrEmpty(ref)) {
        throw new InvalidChangeOperationException("Cherry Pick: Destination branch cannot be null or empty");
    }//from   www.  j  a va 2 s. co m

    Project.NameKey project = change.getProject();
    String destinationBranch = RefNames.shortName(ref);
    IdentifiedUser identifiedUser = (IdentifiedUser) currentUser.get();
    try (Repository git = gitManager.openRepository(project);
            CodeReviewRevWalk revWalk = CodeReviewCommit.newRevWalk(git)) {
        Ref destRef = git.getRefDatabase().exactRef(ref);
        if (destRef == null) {
            throw new InvalidChangeOperationException(
                    String.format("Branch %s does not exist.", destinationBranch));
        }

        CodeReviewCommit mergeTip = revWalk.parseCommit(destRef.getObjectId());

        CodeReviewCommit commitToCherryPick = revWalk
                .parseCommit(ObjectId.fromString(patch.getRevision().get()));

        PersonIdent committerIdent = identifiedUser.newCommitterIdent(TimeUtil.nowTs(), serverTimeZone);

        final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(commitToCherryPick.getTree(), mergeTip,
                commitToCherryPick.getAuthorIdent(), committerIdent, message);
        String commitMessage = ChangeIdUtil.insertId(message, computedChangeId).trim() + '\n';

        CodeReviewCommit cherryPickCommit;
        try (ObjectInserter oi = git.newObjectInserter()) {
            ProjectState projectState = refControl.getProjectControl().getProjectState();
            cherryPickCommit = mergeUtilFactory.create(projectState).createCherryPickFromCommit(git, oi,
                    mergeTip, commitToCherryPick, committerIdent, commitMessage, revWalk);
        } catch (MergeIdenticalTreeException | MergeConflictException e) {
            throw new MergeException("Cherry pick failed: " + e.getMessage());
        }

        Change.Key changeKey;
        final List<String> idList = cherryPickCommit.getFooterLines(FooterConstants.CHANGE_ID);
        if (!idList.isEmpty()) {
            final String idStr = idList.get(idList.size() - 1).trim();
            changeKey = new Change.Key(idStr);
        } else {
            changeKey = new Change.Key("I" + computedChangeId.name());
        }

        Branch.NameKey newDest = new Branch.NameKey(change.getProject(), destRef.getName());
        List<ChangeData> destChanges = queryProvider.get().setLimit(2).byBranchKey(newDest, changeKey);
        if (destChanges.size() > 1) {
            throw new InvalidChangeOperationException("Several changes with key " + changeKey
                    + " reside on the same branch. " + "Cannot create a new patch set.");
        } else if (destChanges.size() == 1) {
            // The change key exists on the destination branch. The cherry pick
            // will be added as a new patch set.
            return insertPatchSet(git, revWalk, destChanges.get(0).change(), cherryPickCommit, refControl,
                    identifiedUser);
        } else {
            // Change key not found on destination branch. We can create a new
            // change.
            String newTopic = null;
            if (!Strings.isNullOrEmpty(change.getTopic())) {
                newTopic = change.getTopic() + "-" + newDest.getShortName();
            }
            Change newChange = createNewChange(git, revWalk, changeKey, project, destRef, cherryPickCommit,
                    refControl, identifiedUser, newTopic);

            addMessageToSourceChange(change, patch.getId(), destinationBranch, cherryPickCommit, identifiedUser,
                    refControl);

            addMessageToDestinationChange(newChange, change.getDest().getShortName(), identifiedUser,
                    refControl);

            return newChange.getId();
        }
    } catch (RepositoryNotFoundException e) {
        throw new NoSuchChangeException(change.getId(), e);
    }
}

From source file:com.google.gerrit.server.change.ConsistencyChecker.java

License:Apache License

private boolean checkPatchSets() {
    List<PatchSet> all;//from   w  ww.j  a  v  a2 s  .  c  o  m
    try {
        all = Lists.newArrayList(db.get().patchSets().byChange(change.getId()));
    } catch (OrmException e) {
        return error("Failed to look up patch sets", e);
    }
    // Iterate in descending order so deletePatchSet can assume the latest patch
    // set exists.
    Collections.sort(all, PS_ID_ORDER.reverse());
    patchSetsBySha = MultimapBuilder.hashKeys(all.size()).treeSetValues(PS_ID_ORDER).build();

    Map<String, Ref> refs;
    try {
        refs = repo.getRefDatabase().exactRef(Lists.transform(all, new Function<PatchSet, String>() {
            @Override
            public String apply(PatchSet ps) {
                return ps.getId().toRefName();
            }
        }).toArray(new String[all.size()]));
    } catch (IOException e) {
        error("error reading refs", e);
        refs = Collections.emptyMap();
    }

    for (PatchSet ps : all) {
        // Check revision format.
        int psNum = ps.getId().get();
        String refName = ps.getId().toRefName();
        ObjectId objId = parseObjectId(ps.getRevision().get(), "patch set " + psNum);
        if (objId == null) {
            continue;
        }
        patchSetsBySha.put(objId, ps);

        // Check ref existence.
        ProblemInfo refProblem = null;
        Ref ref = refs.get(refName);
        if (ref == null) {
            refProblem = problem("Ref missing: " + refName);
        } else if (!objId.equals(ref.getObjectId())) {
            String actual = ref.getObjectId() != null ? ref.getObjectId().name() : "null";
            refProblem = problem(
                    String.format("Expected %s to point to %s, found %s", ref.getName(), objId.name(), actual));
        }

        // Check object existence.
        RevCommit psCommit = parseCommit(objId, String.format("patch set %d", psNum));
        if (psCommit == null) {
            if (fix != null && fix.deletePatchSetIfCommitMissing) {
                deletePatchSet(lastProblem(), ps.getId());
            }
            continue;
        } else if (refProblem != null && fix != null) {
            fixPatchSetRef(refProblem, ps);
        }
        if (ps.getId().equals(change.currentPatchSetId())) {
            currPsCommit = psCommit;
        }
    }

    // Check for duplicates.
    for (Map.Entry<ObjectId, Collection<PatchSet>> e : patchSetsBySha.asMap().entrySet()) {
        if (e.getValue().size() > 1) {
            problem(String.format("Multiple patch sets pointing to %s: %s", e.getKey().name(),
                    Collections2.transform(e.getValue(), TO_PS_ID)));
        }
    }

    return currPs != null && currPsCommit != null;
}

From source file:com.google.gerrit.server.change.ConsistencyChecker.java

License:Apache License

private RevCommit parseCommit(ObjectId objId, String desc) {
    try {/*  w w w .  j a va  2s. c  o  m*/
        return rw.parseCommit(objId);
    } catch (MissingObjectException e) {
        problem(String.format("Object missing: %s: %s", desc, objId.name()));
    } catch (IncorrectObjectTypeException e) {
        problem(String.format("Not a commit: %s: %s", desc, objId.name()));
    } catch (IOException e) {
        problem(String.format("Failed to look up: %s: %s", desc, objId.name()));
    }
    return null;
}

From source file:com.google.gerrit.server.change.CreateChange.java

License:Apache License

private static Change.Key getChangeId(ObjectId id, RevCommit emptyCommit) {
    List<String> idList = emptyCommit.getFooterLines(FooterConstants.CHANGE_ID);
    Change.Key changeKey = !idList.isEmpty() ? new Change.Key(idList.get(idList.size() - 1).trim())
            : new Change.Key("I" + id.name());
    return changeKey;
}

From source file:com.google.gerrit.server.change.FileContentUtil.java

License:Apache License

public BinaryResult getContent(ProjectState project, ObjectId revstr, String path)
        throws ResourceNotFoundException, IOException {
    try (Repository repo = openRepository(project); RevWalk rw = new RevWalk(repo)) {
        RevCommit commit = rw.parseCommit(revstr);
        ObjectReader reader = rw.getObjectReader();
        TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree());
        if (tw == null) {
            throw new ResourceNotFoundException();
        }//from   w w  w .ja  v  a2 s  .c o  m

        org.eclipse.jgit.lib.FileMode mode = tw.getFileMode(0);
        ObjectId id = tw.getObjectId(0);
        if (mode == org.eclipse.jgit.lib.FileMode.GITLINK) {
            return BinaryResult.create(id.name()).setContentType(X_GIT_GITLINK).base64();
        }

        ObjectLoader obj = repo.open(id, OBJ_BLOB);
        byte[] raw;
        try {
            raw = obj.getCachedBytes(MAX_SIZE);
        } catch (LargeObjectException e) {
            raw = null;
        }

        String type;
        if (mode == org.eclipse.jgit.lib.FileMode.SYMLINK) {
            type = X_GIT_SYMLINK;
        } else {
            type = registry.getMimeType(path, raw).toString();
            type = resolveContentType(project, path, FileMode.FILE, type);
        }

        return asBinaryResult(raw, obj).setContentType(type).base64();
    }
}

From source file:com.google.gerrit.server.change.WalkSorter.java

License:Apache License

private Multimap<RevCommit, PatchSetData> byCommit(RevWalk rw, Collection<ChangeData> in)
        throws OrmException, IOException {
    Multimap<RevCommit, PatchSetData> byCommit = ArrayListMultimap.create(in.size(), 1);
    for (ChangeData cd : in) {
        PatchSet maxPs = null;// w w w .j  a  v a2 s . c  om
        for (PatchSet ps : cd.patchSets()) {
            if (shouldInclude(ps) && (maxPs == null || ps.getId().get() > maxPs.getId().get())) {
                maxPs = ps;
            }
        }
        if (maxPs == null) {
            continue; // No patch sets matched.
        }
        ObjectId id = ObjectId.fromString(maxPs.getRevision().get());
        try {
            RevCommit c = rw.parseCommit(id);
            byCommit.put(c, PatchSetData.create(cd, maxPs, c));
        } catch (MissingObjectException | IncorrectObjectTypeException e) {
            log.warn("missing commit " + id.name() + " for patch set " + maxPs.getId(), e);
        }
    }
    return byCommit;
}