Search in sources :

Example 31 with ChangeControl

use of com.google.gerrit.server.project.ChangeControl in project gerrit by GerritCodeReview.

the class ChangeJson method toChangeInfo.

private ChangeInfo toChangeInfo(ChangeData cd, Optional<PatchSet.Id> limitToPsId) throws PatchListNotAvailableException, GpgException, OrmException, IOException, PermissionBackendException {
    ChangeInfo out = new ChangeInfo();
    CurrentUser user = userProvider.get();
    ChangeControl ctl = cd.changeControl().forUser(user);
    if (has(CHECK)) {
        out.problems = checkerProvider.get().check(ctl, fix).problems();
        // If any problems were fixed, the ChangeData needs to be reloaded.
        for (ProblemInfo p : out.problems) {
            if (p.status == ProblemInfo.Status.FIXED) {
                cd = changeDataFactory.create(cd.db(), cd.project(), cd.getId());
                break;
            }
        }
    }
    PermissionBackend.ForChange perm = permissionBackend.user(user).database(db).change(cd);
    Change in = cd.change();
    out.project = in.getProject().get();
    out.branch = in.getDest().getShortName();
    out.topic = in.getTopic();
    if (indexes.getSearchIndex().getSchema().hasField(ChangeField.ASSIGNEE)) {
        if (in.getAssignee() != null) {
            out.assignee = accountLoader.get(in.getAssignee());
        }
    }
    out.hashtags = cd.hashtags();
    out.changeId = in.getKey().get();
    if (in.getStatus().isOpen()) {
        SubmitTypeRecord str = cd.submitTypeRecord();
        if (str.isOk()) {
            out.submitType = str.type;
        }
        out.mergeable = cd.isMergeable();
        if (has(SUBMITTABLE)) {
            out.submittable = submittable(cd);
        }
    }
    Optional<ChangedLines> changedLines = cd.changedLines();
    if (changedLines.isPresent()) {
        out.insertions = changedLines.get().insertions;
        out.deletions = changedLines.get().deletions;
    }
    out.isPrivate = in.isPrivate() ? true : null;
    out.workInProgress = in.isWorkInProgress() ? true : null;
    out.subject = in.getSubject();
    out.status = in.getStatus().asChangeStatus();
    out.owner = accountLoader.get(in.getOwner());
    out.created = in.getCreatedOn();
    out.updated = in.getLastUpdatedOn();
    out._number = in.getId().get();
    out.unresolvedCommentCount = cd.unresolvedCommentCount();
    if (user.isIdentifiedUser()) {
        Collection<String> stars = cd.stars(user.getAccountId());
        out.starred = stars.contains(StarredChangesUtil.DEFAULT_LABEL) ? true : null;
        out.muted = stars.contains(StarredChangesUtil.MUTE_LABEL + "/" + cd.currentPatchSet().getPatchSetId()) ? true : null;
        if (!stars.isEmpty()) {
            out.stars = stars;
        }
    }
    if (in.getStatus().isOpen() && has(REVIEWED) && user.isIdentifiedUser()) {
        Account.Id accountId = user.getAccountId();
        if (out.muted != null) {
            out.reviewed = true;
        } else {
            out.reviewed = cd.reviewedBy().contains(accountId) ? true : null;
        }
    }
    out.labels = labelsFor(perm, ctl, cd, has(LABELS), has(DETAILED_LABELS));
    out.submitted = getSubmittedOn(cd);
    out.plugins = pluginDefinedAttributesFactory != null ? pluginDefinedAttributesFactory.create(cd) : null;
    if (out.labels != null && has(DETAILED_LABELS)) {
        // list permitted labels, since users can't vote on those patch sets.
        if (user.isIdentifiedUser() && (!limitToPsId.isPresent() || limitToPsId.get().equals(in.currentPatchSetId()))) {
            out.permittedLabels = cd.change().getStatus() != Change.Status.ABANDONED ? permittedLabels(perm, cd) : ImmutableMap.of();
        }
        out.reviewers = new HashMap<>();
        for (ReviewerStateInternal state : ReviewerStateInternal.values()) {
            if (state == ReviewerStateInternal.REMOVED) {
                continue;
            }
            Collection<AccountInfo> reviewers = toAccountInfo(cd.reviewers().byState(state));
            reviewers.addAll(toAccountInfoByEmail(cd.reviewersByEmail().byState(state)));
            if (!reviewers.isEmpty()) {
                out.reviewers.put(state.asReviewerState(), reviewers);
            }
        }
        out.removableReviewers = removableReviewers(ctl, out);
    }
    if (has(REVIEWER_UPDATES)) {
        out.reviewerUpdates = reviewerUpdates(cd);
    }
    boolean needMessages = has(MESSAGES);
    boolean needRevisions = has(ALL_REVISIONS) || has(CURRENT_REVISION) || limitToPsId.isPresent();
    Map<PatchSet.Id, PatchSet> src;
    if (needMessages || needRevisions) {
        src = loadPatchSets(cd, limitToPsId);
    } else {
        src = null;
    }
    if (needMessages) {
        out.messages = messages(ctl, cd, src);
    }
    finish(out);
    // it will be passed to ActionVisitors as-is.
    if (needRevisions) {
        out.revisions = revisions(ctl, cd, src, out);
        if (out.revisions != null) {
            for (Map.Entry<String, RevisionInfo> entry : out.revisions.entrySet()) {
                if (entry.getValue().isCurrent) {
                    out.currentRevision = entry.getKey();
                    break;
                }
            }
        }
    }
    if (has(CURRENT_ACTIONS) || has(CHANGE_ACTIONS)) {
        actionJson.addChangeActions(out, ctl);
    }
    return out;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) CurrentUser(com.google.gerrit.server.CurrentUser) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ChangeControl(com.google.gerrit.server.project.ChangeControl) ChangedLines(com.google.gerrit.server.query.change.ChangeData.ChangedLines) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) SubmitTypeRecord(com.google.gerrit.common.data.SubmitTypeRecord) RevisionInfo(com.google.gerrit.extensions.common.RevisionInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 32 with ChangeControl

use of com.google.gerrit.server.project.ChangeControl in project gerrit by GerritCodeReview.

the class PostReview method onBehalfOf.

private RevisionResource onBehalfOf(RevisionResource rev, ReviewInput in) throws BadRequestException, AuthException, UnprocessableEntityException, OrmException, PermissionBackendException {
    if (in.labels == null || in.labels.isEmpty()) {
        throw new AuthException(String.format("label required to post review on behalf of \"%s\"", in.onBehalfOf));
    }
    if (in.drafts == null) {
        in.drafts = DraftHandling.KEEP;
    }
    if (in.drafts != DraftHandling.KEEP) {
        throw new AuthException("not allowed to modify other user's drafts");
    }
    CurrentUser caller = rev.getUser();
    PermissionBackend.ForChange perm = rev.permissions().database(db);
    LabelTypes labelTypes = rev.getControl().getLabelTypes();
    Iterator<Map.Entry<String, Short>> itr = in.labels.entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Short> ent = itr.next();
        LabelType type = labelTypes.byLabel(ent.getKey());
        if (type == null && in.strictLabels) {
            throw new BadRequestException(String.format("label \"%s\" is not a configured label", ent.getKey()));
        } else if (type == null) {
            itr.remove();
            continue;
        }
        if (!caller.isInternalUser()) {
            try {
                perm.check(new LabelPermission.WithValue(ON_BEHALF_OF, type, ent.getValue()));
            } catch (AuthException e) {
                throw new AuthException(String.format("not permitted to modify label \"%s\" on behalf of \"%s\"", type.getName(), in.onBehalfOf));
            }
        }
    }
    if (in.labels.isEmpty()) {
        throw new AuthException(String.format("label required to post review on behalf of \"%s\"", in.onBehalfOf));
    }
    IdentifiedUser reviewer = accounts.parseOnBehalfOf(caller, in.onBehalfOf);
    try {
        perm.user(reviewer).check(ChangePermission.READ);
    } catch (AuthException e) {
        throw new UnprocessableEntityException(String.format("on_behalf_of account %s cannot see change", reviewer.getAccountId()));
    }
    ChangeControl ctl = rev.getControl().forUser(reviewer);
    return new RevisionResource(changes.parse(ctl), rev.getPatchSet());
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) LabelTypes(com.google.gerrit.common.data.LabelTypes) CurrentUser(com.google.gerrit.server.CurrentUser) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) AuthException(com.google.gerrit.extensions.restapi.AuthException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ChangeControl(com.google.gerrit.server.project.ChangeControl) LabelType(com.google.gerrit.common.data.LabelType) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Map(java.util.Map) HashMap(java.util.HashMap) LabelPermission(com.google.gerrit.server.permissions.LabelPermission)

Example 33 with ChangeControl

use of com.google.gerrit.server.project.ChangeControl in project gerrit by GerritCodeReview.

the class CreateMergePatchSet method applyImpl.

@Override
protected Response<ChangeInfo> applyImpl(BatchUpdate.Factory updateFactory, ChangeResource rsrc, MergePatchSetInput in) throws OrmException, IOException, InvalidChangeOperationException, RestApiException, UpdateException, PermissionBackendException {
    rsrc.permissions().database(db).check(ChangePermission.ADD_PATCH_SET);
    MergeInput merge = in.merge;
    if (merge == null || Strings.isNullOrEmpty(merge.source)) {
        throw new BadRequestException("merge.source must be non-empty");
    }
    ChangeControl ctl = rsrc.getControl();
    PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
    ProjectControl projectControl = ctl.getProjectControl();
    Change change = ctl.getChange();
    Project.NameKey project = change.getProject();
    Branch.NameKey dest = change.getDest();
    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
        RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, merge.source);
        if (!projectControl.canReadCommit(db.get(), git, sourceCommit)) {
            throw new ResourceNotFoundException("cannot find source commit: " + merge.source + " to merge.");
        }
        RevCommit currentPsCommit = rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
        Timestamp now = TimeUtil.nowTs();
        IdentifiedUser me = user.get().asIdentifiedUser();
        PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
        RevCommit newCommit = createMergeCommit(in, projectControl, dest, git, oi, rw, currentPsCommit, sourceCommit, author, ObjectId.fromString(change.getKey().get().substring(1)));
        PatchSet.Id nextPsId = ChangeUtil.nextPatchSetId(ps.getId());
        PatchSetInserter psInserter = patchSetInserterFactory.create(ctl, nextPsId, newCommit);
        try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
            bu.setRepository(git, rw, oi);
            bu.addOp(ctl.getId(), psInserter.setMessage("Uploaded patch set " + nextPsId.get() + ".").setDraft(ps.isDraft()).setNotify(NotifyHandling.NONE).setCheckAddPatchSetPermission(false));
            bu.execute();
        }
        ChangeJson json = jsonFactory.create(ListChangesOption.CURRENT_REVISION);
        return Response.ok(json.format(psInserter.getChange()));
    }
}
Also used : MergeInput(com.google.gerrit.extensions.common.MergeInput) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ProjectControl(com.google.gerrit.server.project.ProjectControl) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ChangeControl(com.google.gerrit.server.project.ChangeControl) Branch(com.google.gerrit.reviewdb.client.Branch) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 34 with ChangeControl

use of com.google.gerrit.server.project.ChangeControl in project gerrit by GerritCodeReview.

the class GetHashtags method apply.

@Override
public Response<Set<String>> apply(ChangeResource req) throws AuthException, OrmException, IOException, BadRequestException {
    ChangeControl control = req.getControl();
    ChangeNotes notes = control.getNotes().load();
    Set<String> hashtags = notes.getHashtags();
    if (hashtags == null) {
        hashtags = Collections.emptySet();
    }
    return Response.ok(hashtags);
}
Also used : ChangeControl(com.google.gerrit.server.project.ChangeControl) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes)

Aggregations

ChangeControl (com.google.gerrit.server.project.ChangeControl)34 Change (com.google.gerrit.reviewdb.client.Change)11 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)9 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)7 AuthException (com.google.gerrit.extensions.restapi.AuthException)6 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)6 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)5 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)5 Project (com.google.gerrit.reviewdb.client.Project)5 ChangeData (com.google.gerrit.server.query.change.ChangeData)5 HashMap (java.util.HashMap)5 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)4 ObjectId (org.eclipse.jgit.lib.ObjectId)4 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)4 ObjectReader (org.eclipse.jgit.lib.ObjectReader)4 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)3 LabelType (com.google.gerrit.common.data.LabelType)3 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)3 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)3 Branch (com.google.gerrit.reviewdb.client.Branch)3