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

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

Introduction

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

Prototype

public static ObjectId fromString(String str) 

Source Link

Document

Convert an ObjectId from hex characters.

Usage

From source file:com.google.gerrit.pgm.ExportReviewNotes.java

License:Apache License

private void export(ReviewDb db, Project.NameKey project, List<Change> changes)
        throws IOException, OrmException, CodeReviewNoteCreationException, InterruptedException {
    final Repository git;
    try {// w w  w .ja  va2s . c o m
        git = gitManager.openRepository(project);
    } catch (RepositoryNotFoundException e) {
        return;
    }
    try {
        CreateCodeReviewNotes notes = codeReviewNotesFactory.create(db, git);
        try {
            notes.loadBase();
            for (Change change : changes) {
                monitor.update(1);
                PatchSet ps = db.patchSets().get(change.currentPatchSetId());
                if (ps == null) {
                    continue;
                }
                notes.add(change, ObjectId.fromString(ps.getRevision().get()));
            }
            notes.commit("Exported prior reviews from Gerrit Code Review\n");
            notes.updateRef();
        } finally {
            notes.release();
        }
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.pgm.ScanTrackingIds.java

License:Apache License

private RevCommit parse(final Repository git, PatchSet ps)
        throws MissingObjectException, IncorrectObjectTypeException, IOException {
    RevWalk rw = new RevWalk(git);
    try {// w w w .j  ava 2  s.  c  om
        return rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
    } finally {
        rw.release();
    }
}

From source file:com.google.gerrit.server.ApprovalCopier.java

License:Apache License

private Iterable<PatchSetApproval> getForPatchSet(ReviewDb db, ChangeControl ctl, PatchSet ps)
        throws OrmException {
    ChangeData cd = changeDataFactory.create(db, ctl);
    try {//from w w  w  .  j  a  va 2  s.c o  m
        ProjectState project = projectCache.checkedGet(cd.change().getDest().getParentKey());
        ListMultimap<PatchSet.Id, PatchSetApproval> all = cd.approvals();

        Table<String, Account.Id, PatchSetApproval> byUser = HashBasedTable.create();
        for (PatchSetApproval psa : all.get(ps.getId())) {
            byUser.put(psa.getLabel(), psa.getAccountId(), psa);
        }

        TreeMap<Integer, PatchSet> patchSets = getPatchSets(cd);
        NavigableSet<Integer> allPsIds = patchSets.navigableKeySet();

        try (Repository repo = repoManager.openRepository(project.getProject().getNameKey())) {
            // Walk patch sets strictly less than current in descending order.
            Collection<PatchSet> allPrior = patchSets.descendingMap().tailMap(ps.getId().get(), false).values();
            for (PatchSet priorPs : allPrior) {
                List<PatchSetApproval> priorApprovals = all.get(priorPs.getId());
                if (priorApprovals.isEmpty()) {
                    continue;
                }

                ChangeKind kind = changeKindCache.getChangeKind(project, repo,
                        ObjectId.fromString(priorPs.getRevision().get()),
                        ObjectId.fromString(ps.getRevision().get()));

                for (PatchSetApproval psa : priorApprovals) {
                    if (!byUser.contains(psa.getLabel(), psa.getAccountId())
                            && canCopy(project, psa, ps.getId(), allPsIds, kind)) {
                        byUser.put(psa.getLabel(), psa.getAccountId(), copy(psa, ps.getId()));
                    }
                }
            }
            return labelNormalizer.normalize(ctl, byUser.values()).getNormalized();
        }
    } catch (IOException e) {
        throw new OrmException(e);
    }
}

From source file:com.google.gerrit.server.args4j.ObjectIdHandler.java

License:Apache License

@Override
public int parseArguments(Parameters params) throws CmdLineException {
    final String n = params.getParameter(0);
    setter.addValue(ObjectId.fromString(n));
    return 1;/*w  ww  .j a  v a 2 s  .  c om*/
}

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

License:Apache License

@Override
public Response<EditInfo> apply(FixResource fixResource, Void nothing)
        throws AuthException, OrmException, ResourceConflictException, IOException, ResourceNotFoundException {
    RevisionResource revisionResource = fixResource.getRevisionResource();
    Project.NameKey project = revisionResource.getProject();
    ProjectState projectState = revisionResource.getControl().getProjectControl().getProjectState();
    PatchSet patchSet = revisionResource.getPatchSet();
    ObjectId patchSetCommitId = ObjectId.fromString(patchSet.getRevision().get());

    try (Repository repository = gitRepositoryManager.openRepository(project)) {
        List<TreeModification> treeModifications = fixReplacementInterpreter.toTreeModifications(repository,
                projectState, patchSetCommitId, fixResource.getFixReplacements());
        ChangeEdit changeEdit = changeEditModifier.combineWithModifiedPatchSetTree(repository,
                revisionResource.getControl(), patchSet, treeModifications);
        EditInfo editInfo = changeEditJson.toEditInfo(changeEdit, false);
        return Response.ok(editInfo);
    } catch (InvalidChangeOperationException e) {
        throw new ResourceConflictException(e.getMessage());
    }//  w ww .  j  a va2  s.c  om
}

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

License:Apache License

private RevisionInfo toRevisionInfo(ChangeControl ctl, PatchSet in)
        throws PatchListNotAvailableException, OrmException, IOException {
    Change c = ctl.getChange();//from  w  w  w.  j a v  a 2s.  c o m
    RevisionInfo out = new RevisionInfo();
    out.isCurrent = in.getId().equals(c.currentPatchSetId());
    out._number = in.getId().get();
    out.ref = in.getRefName();
    out.created = in.getCreatedOn();
    out.uploader = accountLoader.get(in.getUploader());
    out.draft = in.isDraft() ? true : null;
    out.fetch = makeFetchMap(ctl, in);

    boolean setCommit = has(ALL_COMMITS) || (out.isCurrent && has(CURRENT_COMMIT));
    boolean addFooters = out.isCurrent && has(COMMIT_FOOTERS);
    if (setCommit || addFooters) {
        Project.NameKey project = c.getProject();
        try (Repository repo = repoManager.openRepository(project); RevWalk rw = new RevWalk(repo)) {
            String rev = in.getRevision().get();
            RevCommit commit = rw.parseCommit(ObjectId.fromString(rev));
            rw.parseBody(commit);
            if (setCommit) {
                out.commit = toCommit(ctl, rw, commit, has(WEB_LINKS));
            }
            if (addFooters) {
                out.commitWithFooters = mergeUtilFactory.create(projectCache.get(project))
                        .createCherryPickCommitMessage(commit, ctl, in.getId());
            }
        }
    }

    if (has(ALL_FILES) || (out.isCurrent && has(CURRENT_FILES))) {
        out.files = fileInfoJson.toFileInfoMap(c, in);
        out.files.remove(Patch.COMMIT_MSG);
    }

    if ((out.isCurrent || (out.draft != null && out.draft)) && has(CURRENT_ACTIONS)
            && userProvider.get().isIdentifiedUser()) {

        actionJson.addRevisionActions(out, new RevisionResource(new ChangeResource(ctl), in));
    }

    return out;
}

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

License:Apache License

private static ChangeKind getChangeKindInternal(ChangeKindCache cache, ReviewDb db, Change change,
        PatchSet patch, ChangeData.Factory changeDataFactory, ProjectCache projectCache,
        GitRepositoryManager repoManager) {
    // TODO - dborowitz: add NEW_CHANGE type for default.
    ChangeKind kind = ChangeKind.REWORK;
    // Trivial case: if we're on the first patch, we don't need to open
    // the repository.
    if (patch.getId().get() > 1) {
        try (Repository repo = repoManager.openRepository(change.getProject())) {
            ProjectState projectState = projectCache.checkedGet(change.getProject());
            ChangeData cd = changeDataFactory.create(db, change);
            Collection<PatchSet> patchSetCollection = cd.patchSets();
            PatchSet priorPs = patch;//  w ww .j  av a2s.  c  om
            for (PatchSet ps : patchSetCollection) {
                if (ps.getId().get() < patch.getId().get()
                        && (ps.getId().get() > priorPs.getId().get() || priorPs == patch)) {
                    // We only want the previous patch set, so walk until the last one
                    priorPs = ps;
                }
            }

            // If we still think the previous patch is the current patch,
            // we only have one patch set.  Return the default.
            // This can happen if a user creates a draft, uploads a second patch,
            // and deletes the draft.
            if (priorPs != patch) {
                kind = cache.getChangeKind(projectState, repo, ObjectId.fromString(priorPs.getRevision().get()),
                        ObjectId.fromString(patch.getRevision().get()));
            }
        } catch (IOException | OrmException e) {
            // Do nothing; assume we have a complex change
            log.warn("Unable to get change kind for patchSet " + patch.getPatchSetId() + "of change "
                    + change.getChangeId(), e);
        }
    }
    return kind;
}

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   w w w  .  j a va2s  . com*/

    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 void fixPatchSetRef(ProblemInfo p, PatchSet ps) {
    try {/*  w  ww. ja  v  a2 s  . com*/
        RefUpdate ru = repo.updateRef(ps.getId().toRefName());
        ru.setForceUpdate(true);
        ru.setNewObjectId(ObjectId.fromString(ps.getRevision().get()));
        ru.setRefLogIdent(newRefLogIdent());
        ru.setRefLogMessage("Repair patch set ref", true);
        RefUpdate.Result result = ru.update();
        switch (result) {
        case NEW:
        case FORCED:
        case FAST_FORWARD:
        case NO_CHANGE:
            p.status = Status.FIXED;
            p.outcome = "Repaired patch set ref";
            return;
        default:
            p.status = Status.FIX_FAILED;
            p.outcome = "Failed to update patch set ref: " + result;
            return;
        }
    } catch (IOException e) {
        String msg = "Error fixing patch set ref";
        log.warn(msg + ' ' + ps.getId().toRefName(), e);
        p.status = Status.FIX_FAILED;
        p.outcome = msg;
    }
}

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

License:Apache License

private ObjectId parseObjectId(String objIdStr, String desc) {
    try {//from  w ww  .j  av  a2 s . c o  m
        return ObjectId.fromString(objIdStr);
    } catch (IllegalArgumentException e) {
        problem(String.format("Invalid revision on %s: %s", desc, objIdStr));
        return null;
    }
}