Search in sources :

Example 16 with Change

use of com.google.gerrit.reviewdb.client.Change in project gerrit by GerritCodeReview.

the class ReplaceOp method resetChange.

private void resetChange(ChangeContext ctx) {
    Change change = ctx.getChange();
    if (!change.currentPatchSetId().equals(priorPatchSetId)) {
        return;
    }
    if (magicBranch != null && magicBranch.topic != null) {
        change.setTopic(magicBranch.topic);
    }
    if (change.getStatus() == Change.Status.DRAFT && newPatchSet.isDraft()) {
    // Leave in draft status.
    } else {
        change.setStatus(Change.Status.NEW);
    }
    change.setCurrentPatchSet(info);
    List<String> idList = commit.getFooterLines(CHANGE_ID);
    if (idList.isEmpty()) {
        change.setKey(new Change.Key("I" + commitId.name()));
    } else {
        change.setKey(new Change.Key(idList.get(idList.size() - 1).trim()));
    }
}
Also used : Change(com.google.gerrit.reviewdb.client.Change)

Example 17 with Change

use of com.google.gerrit.reviewdb.client.Change in project gerrit by GerritCodeReview.

the class ReplaceOp method updateChange.

@Override
public boolean updateChange(ChangeContext ctx) throws RestApiException, OrmException, IOException {
    notes = ctx.getNotes();
    Change change = notes.getChange();
    if (change == null || change.getStatus().isClosed()) {
        rejectMessage = CHANGE_IS_CLOSED;
        return false;
    }
    if (groups.isEmpty()) {
        PatchSet prevPs = psUtil.current(ctx.getDb(), notes);
        groups = prevPs != null ? prevPs.getGroups() : ImmutableList.<String>of();
    }
    ChangeUpdate update = ctx.getUpdate(patchSetId);
    update.setSubjectForCommit("Create patch set " + patchSetId.get());
    String reviewMessage = null;
    String psDescription = null;
    if (magicBranch != null) {
        recipients.add(magicBranch.getMailRecipients());
        reviewMessage = magicBranch.message;
        psDescription = magicBranch.message;
        approvals.putAll(magicBranch.labels);
        Set<String> hashtags = magicBranch.hashtags;
        if (hashtags != null && !hashtags.isEmpty()) {
            hashtags.addAll(notes.getHashtags());
            update.setHashtags(hashtags);
        }
        if (magicBranch.topic != null && !magicBranch.topic.equals(ctx.getChange().getTopic())) {
            update.setTopic(magicBranch.topic);
        }
        if (magicBranch.removePrivate) {
            change.setPrivate(false);
            update.setPrivate(false);
        } else if (magicBranch.isPrivate) {
            change.setPrivate(true);
            update.setPrivate(true);
        }
        if (magicBranch.ready) {
            change.setWorkInProgress(false);
            update.setWorkInProgress(false);
        } else if (magicBranch.workInProgress) {
            change.setWorkInProgress(true);
            update.setWorkInProgress(true);
        }
        if (shouldPublishComments()) {
            comments = publishComments(ctx);
        }
    }
    boolean draft = magicBranch != null && magicBranch.draft;
    if (change.getStatus() == Change.Status.DRAFT && !draft) {
        update.setStatus(Change.Status.NEW);
    }
    newPatchSet = psUtil.insert(ctx.getDb(), ctx.getRevWalk(), update, patchSetId, commitId, draft, groups, pushCertificate != null ? pushCertificate.toTextWithSignature() : null, psDescription);
    update.setPsDescription(psDescription);
    recipients.add(getRecipientsFromFooters(ctx.getDb(), accountResolver, draft, commit.getFooterLines()));
    recipients.remove(ctx.getAccountId());
    ChangeData cd = changeDataFactory.create(ctx.getDb(), ctx.getControl());
    MailRecipients oldRecipients = getRecipientsFromReviewers(cd.reviewers());
    Iterable<PatchSetApproval> newApprovals = approvalsUtil.addApprovalsForNewPatchSet(ctx.getDb(), update, projectControl.getLabelTypes(), newPatchSet, ctx.getControl(), approvals);
    approvalCopier.copy(ctx.getDb(), ctx.getControl(), newPatchSet, newApprovals);
    approvalsUtil.addReviewers(ctx.getDb(), update, projectControl.getLabelTypes(), change, newPatchSet, info, recipients.getReviewers(), oldRecipients.getAll());
    // reviewer which is needed in several other code paths.
    if (magicBranch != null && !magicBranch.labels.isEmpty()) {
        update.putReviewer(ctx.getAccountId(), REVIEWER);
    }
    recipients.add(oldRecipients);
    msg = createChangeMessage(ctx, reviewMessage);
    cmUtil.addChangeMessage(ctx.getDb(), update, msg);
    if (mergedByPushOp == null) {
        resetChange(ctx);
    } else {
        mergedByPushOp.setPatchSetProvider(Providers.of(newPatchSet)).updateChange(ctx);
    }
    return true;
}
Also used : MailRecipients(com.google.gerrit.server.mail.MailUtil.MailRecipients) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) ChangeData(com.google.gerrit.server.query.change.ChangeData) PatchSetApproval(com.google.gerrit.reviewdb.client.PatchSetApproval) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate)

Example 18 with Change

use of com.google.gerrit.reviewdb.client.Change in project gerrit by GerritCodeReview.

the class ReceiveCommits method parseCommands.

private void parseCommands(Collection<ReceiveCommand> commands) throws PermissionBackendException {
    List<String> optionList = rp.getPushOptions();
    if (optionList != null) {
        for (String option : optionList) {
            int e = option.indexOf('=');
            if (e > 0) {
                pushOptions.put(option.substring(0, e), option.substring(e + 1));
            } else {
                pushOptions.put(option, "");
            }
        }
    }
    logDebug("Parsing {} commands", commands.size());
    for (ReceiveCommand cmd : commands) {
        if (cmd.getResult() != NOT_ATTEMPTED) {
            // Already rejected by the core receive process.
            logDebug("Already processed by core: {} {}", cmd.getResult(), cmd);
            continue;
        }
        if (!Repository.isValidRefName(cmd.getRefName()) || cmd.getRefName().contains("//")) {
            reject(cmd, "not valid ref");
            continue;
        }
        if (MagicBranch.isMagicBranch(cmd.getRefName())) {
            parseMagicBranch(cmd);
            continue;
        }
        if (projectControl.getProjectState().isAllUsers() && RefNames.REFS_USERS_SELF.equals(cmd.getRefName())) {
            String newName = RefNames.refsUsers(user.getAccountId());
            logDebug("Swapping out command for {} to {}", RefNames.REFS_USERS_SELF, newName);
            final ReceiveCommand orgCmd = cmd;
            cmd = new ReceiveCommand(cmd.getOldId(), cmd.getNewId(), newName, cmd.getType()) {

                @Override
                public void setResult(Result s, String m) {
                    super.setResult(s, m);
                    orgCmd.setResult(s, m);
                }
            };
        }
        Matcher m = NEW_PATCHSET.matcher(cmd.getRefName());
        if (m.matches()) {
            // The referenced change must exist and must still be open.
            //
            Change.Id changeId = Change.Id.parse(m.group(1));
            parseReplaceCommand(cmd, changeId);
            continue;
        }
        switch(cmd.getType()) {
            case CREATE:
                parseCreate(cmd);
                break;
            case UPDATE:
                parseUpdate(cmd);
                break;
            case DELETE:
                parseDelete(cmd);
                break;
            case UPDATE_NONFASTFORWARD:
                parseRewind(cmd);
                break;
            default:
                reject(cmd, "prohibited by Gerrit: unknown command type " + cmd.getType());
                continue;
        }
        if (cmd.getResult() != NOT_ATTEMPTED) {
            continue;
        }
        if (isConfig(cmd)) {
            logDebug("Processing {} command", cmd.getRefName());
            if (!projectControl.isOwner()) {
                reject(cmd, "not project owner");
                continue;
            }
            switch(cmd.getType()) {
                case CREATE:
                case UPDATE:
                case UPDATE_NONFASTFORWARD:
                    try {
                        ProjectConfig cfg = new ProjectConfig(project.getNameKey());
                        cfg.load(rp.getRevWalk(), cmd.getNewId());
                        if (!cfg.getValidationErrors().isEmpty()) {
                            addError("Invalid project configuration:");
                            for (ValidationError err : cfg.getValidationErrors()) {
                                addError("  " + err.getMessage());
                            }
                            reject(cmd, "invalid project configuration");
                            logError("User " + user.getUserName() + " tried to push invalid project configuration " + cmd.getNewId().name() + " for " + project.getName());
                            continue;
                        }
                        Project.NameKey newParent = cfg.getProject().getParent(allProjectsName);
                        Project.NameKey oldParent = project.getParent(allProjectsName);
                        if (oldParent == null) {
                            // update of the 'All-Projects' project
                            if (newParent != null) {
                                reject(cmd, "invalid project configuration: root project cannot have parent");
                                continue;
                            }
                        } else {
                            if (!oldParent.equals(newParent)) {
                                try {
                                    permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
                                } catch (AuthException e) {
                                    reject(cmd, "invalid project configuration: only Gerrit admin can set parent");
                                    continue;
                                }
                            }
                            if (projectCache.get(newParent) == null) {
                                reject(cmd, "invalid project configuration: parent does not exist");
                                continue;
                            }
                        }
                        for (Entry<ProjectConfigEntry> e : pluginConfigEntries) {
                            PluginConfig pluginCfg = cfg.getPluginConfig(e.getPluginName());
                            ProjectConfigEntry configEntry = e.getProvider().get();
                            String value = pluginCfg.getString(e.getExportName());
                            String oldValue = projectControl.getProjectState().getConfig().getPluginConfig(e.getPluginName()).getString(e.getExportName());
                            if (configEntry.getType() == ProjectConfigEntryType.ARRAY) {
                                oldValue = Arrays.stream(projectControl.getProjectState().getConfig().getPluginConfig(e.getPluginName()).getStringList(e.getExportName())).collect(joining("\n"));
                            }
                            if ((value == null ? oldValue != null : !value.equals(oldValue)) && !configEntry.isEditable(projectControl.getProjectState())) {
                                reject(cmd, String.format("invalid project configuration: Not allowed to set parameter" + " '%s' of plugin '%s' on project '%s'.", e.getExportName(), e.getPluginName(), project.getName()));
                                continue;
                            }
                            if (ProjectConfigEntryType.LIST.equals(configEntry.getType()) && value != null && !configEntry.getPermittedValues().contains(value)) {
                                reject(cmd, String.format("invalid project configuration: The value '%s' is " + "not permitted for parameter '%s' of plugin '%s'.", value, e.getExportName(), e.getPluginName()));
                            }
                        }
                    } catch (Exception e) {
                        reject(cmd, "invalid project configuration");
                        logError("User " + user.getUserName() + " tried to push invalid project configuration " + cmd.getNewId().name() + " for " + project.getName(), e);
                        continue;
                    }
                    break;
                case DELETE:
                    break;
                default:
                    reject(cmd, "prohibited by Gerrit: don't know how to handle config update of type " + cmd.getType());
                    continue;
            }
        }
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) Matcher(java.util.regex.Matcher) AuthException(com.google.gerrit.extensions.restapi.AuthException) Change(com.google.gerrit.reviewdb.client.Change) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) RefOperationValidationException(com.google.gerrit.server.git.validators.RefOperationValidationException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) OrmException(com.google.gwtorm.server.OrmException) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) UpdateException(com.google.gerrit.server.update.UpdateException) AuthException(com.google.gerrit.extensions.restapi.AuthException) CmdLineException(org.kohsuke.args4j.CmdLineException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) CommitValidationException(com.google.gerrit.server.git.validators.CommitValidationException) ServiceMayNotContinueException(org.eclipse.jgit.transport.ServiceMayNotContinueException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Result(org.eclipse.jgit.transport.ReceiveCommand.Result) PluginConfig(com.google.gerrit.server.config.PluginConfig) Project(com.google.gerrit.reviewdb.client.Project) ProjectConfigEntry(com.google.gerrit.server.config.ProjectConfigEntry)

Example 19 with Change

use of com.google.gerrit.reviewdb.client.Change in project gerrit by GerritCodeReview.

the class ReceiveCommits method parseReplaceCommand.

private void parseReplaceCommand(ReceiveCommand cmd, Change.Id changeId) {
    logDebug("Parsing replace command");
    if (cmd.getType() != ReceiveCommand.Type.CREATE) {
        reject(cmd, "invalid usage");
        return;
    }
    RevCommit newCommit;
    try {
        newCommit = rp.getRevWalk().parseCommit(cmd.getNewId());
        logDebug("Replacing with {}", newCommit);
    } catch (IOException e) {
        logError("Cannot parse " + cmd.getNewId().name() + " as commit", e);
        reject(cmd, "invalid commit");
        return;
    }
    Change changeEnt;
    try {
        changeEnt = notesFactory.createChecked(db, project.getNameKey(), changeId).getChange();
    } catch (NoSuchChangeException e) {
        logError("Change not found " + changeId, e);
        reject(cmd, "change " + changeId + " not found");
        return;
    } catch (OrmException e) {
        logError("Cannot lookup existing change " + changeId, e);
        reject(cmd, "database error");
        return;
    }
    if (!project.getNameKey().equals(changeEnt.getProject())) {
        reject(cmd, "change " + changeId + " does not belong to project " + project.getName());
        return;
    }
    logDebug("Replacing change {}", changeEnt.getId());
    requestReplace(cmd, true, changeEnt, newCommit);
}
Also used : NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) OrmException(com.google.gwtorm.server.OrmException) IOException(java.io.IOException) Change(com.google.gerrit.reviewdb.client.Change) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 20 with Change

use of com.google.gerrit.reviewdb.client.Change in project gerrit by GerritCodeReview.

the class ReceiveCommits method foundInExistingRef.

private boolean foundInExistingRef(Collection<Ref> existingRefs) throws OrmException {
    for (Ref ref : existingRefs) {
        ChangeNotes notes = notesFactory.create(db, project.getNameKey(), Change.Id.fromRef(ref.getName()));
        Change change = notes.getChange();
        if (change.getDest().equals(magicBranch.dest)) {
            logDebug("Found change {} from existing refs.", change.getKey());
            // Reindex the change asynchronously, ignoring errors.
            @SuppressWarnings("unused") Future<?> possiblyIgnoredError = indexer.indexAsync(project.getNameKey(), change.getId());
            return true;
        }
    }
    return false;
}
Also used : Ref(org.eclipse.jgit.lib.Ref) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) Change(com.google.gerrit.reviewdb.client.Change)

Aggregations

Change (com.google.gerrit.reviewdb.client.Change)191 Test (org.junit.Test)96 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)53 ObjectId (org.eclipse.jgit.lib.ObjectId)32 Timestamp (java.sql.Timestamp)31 Account (com.google.gerrit.reviewdb.client.Account)30 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)28 OrmException (com.google.gwtorm.server.OrmException)28 Project (com.google.gerrit.reviewdb.client.Project)27 Repository (org.eclipse.jgit.lib.Repository)27 RevWalk (org.eclipse.jgit.revwalk.RevWalk)24 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)23 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)22 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)21 ChangeMessage (com.google.gerrit.reviewdb.client.ChangeMessage)20 RevCommit (org.eclipse.jgit.revwalk.RevCommit)19 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)17 PatchSetApproval (com.google.gerrit.reviewdb.client.PatchSetApproval)17 ChangeData (com.google.gerrit.server.query.change.ChangeData)16 RevId (com.google.gerrit.reviewdb.client.RevId)15