Search in sources :

Example 1 with ReceiveCommand

use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.

the class ReviewDbBatchUpdate method executeRefUpdates.

private void executeRefUpdates(boolean dryrun) throws IOException, RestApiException {
    if (getRefUpdates().isEmpty()) {
        logDebug("No ref updates to execute");
        return;
    }
    // May not be opened if the caller added ref updates but no new objects.
    // TODO(dborowitz): Really?
    initRepository();
    batchRefUpdate = repoView.getRepository().getRefDatabase().newBatchUpdate();
    batchRefUpdate.setPushCertificate(pushCert);
    batchRefUpdate.setRefLogMessage(refLogMessage, true);
    batchRefUpdate.setAllowNonFastForwards(true);
    repoView.getCommands().addTo(batchRefUpdate);
    logDebug("Executing batch of {} ref updates", batchRefUpdate.getCommands().size());
    if (dryrun) {
        return;
    }
    // that might have access to unflushed objects.
    try (RevWalk updateRw = new RevWalk(repoView.getRepository())) {
        batchRefUpdate.execute(updateRw, NullProgressMonitor.INSTANCE);
    }
    boolean ok = true;
    for (ReceiveCommand cmd : batchRefUpdate.getCommands()) {
        if (cmd.getResult() != ReceiveCommand.Result.OK) {
            ok = false;
            break;
        }
    }
    if (!ok) {
        throw new RestApiException("BatchRefUpdate failed: " + batchRefUpdate);
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Example 2 with ReceiveCommand

use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.

the class Schema_123 method migrateData.

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    ListMultimap<Account.Id, Change.Id> imports = MultimapBuilder.hashKeys().arrayListValues().build();
    try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
        ResultSet rs = stmt.executeQuery("SELECT account_id, change_id FROM starred_changes")) {
        while (rs.next()) {
            Account.Id accountId = new Account.Id(rs.getInt(1));
            Change.Id changeId = new Change.Id(rs.getInt(2));
            imports.put(accountId, changeId);
        }
    }
    if (imports.isEmpty()) {
        return;
    }
    try (Repository git = repoManager.openRepository(allUsersName);
        RevWalk rw = new RevWalk(git)) {
        BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
        ObjectId id = StarredChangesUtil.writeLabels(git, StarredChangesUtil.DEFAULT_LABELS);
        for (Map.Entry<Account.Id, Change.Id> e : imports.entries()) {
            bru.addCommand(new ReceiveCommand(ObjectId.zeroId(), id, RefNames.refsStarredChanges(e.getValue(), e.getKey())));
        }
        bru.execute(rw, new TextProgressMonitor());
    } catch (IOException ex) {
        throw new OrmException(ex);
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) ObjectId(org.eclipse.jgit.lib.ObjectId) Statement(java.sql.Statement) Change(com.google.gerrit.reviewdb.client.Change) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TextProgressMonitor(org.eclipse.jgit.lib.TextProgressMonitor) Repository(org.eclipse.jgit.lib.Repository) OrmException(com.google.gwtorm.server.OrmException) ResultSet(java.sql.ResultSet) ObjectId(org.eclipse.jgit.lib.ObjectId) Map(java.util.Map) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 3 with ReceiveCommand

use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.

the class RebuildNoteDb method deleteRefs.

private void deleteRefs(String prefix, Repository allUsersRepo) throws IOException {
    RefDatabase refDb = allUsersRepo.getRefDatabase();
    Map<String, Ref> allRefs = refDb.getRefs(prefix);
    BatchRefUpdate bru = refDb.newBatchUpdate();
    for (Map.Entry<String, Ref> ref : allRefs.entrySet()) {
        bru.addCommand(new ReceiveCommand(ref.getValue().getObjectId(), ObjectId.zeroId(), prefix + ref.getKey()));
    }
    execute(bru, allUsersRepo);
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) Ref(org.eclipse.jgit.lib.Ref) RefDatabase(org.eclipse.jgit.lib.RefDatabase) Map(java.util.Map) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 4 with ReceiveCommand

use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.

the class ReplaceOp method updateRepo.

@Override
public void updateRepo(RepoContext ctx) throws Exception {
    commit = ctx.getRevWalk().parseCommit(commitId);
    ctx.getRevWalk().parseBody(commit);
    changeKind = changeKindCache.getChangeKind(projectControl.getProject().getNameKey(), ctx.getRevWalk(), ctx.getRepoView().getConfig(), priorCommitId, commitId);
    if (checkMergedInto) {
        String mergedInto = findMergedInto(ctx, dest.get(), commit);
        if (mergedInto != null) {
            mergedByPushOp = mergedByPushOpFactory.create(requestScopePropagator, patchSetId, mergedInto);
        }
    }
    cmd = new ReceiveCommand(ObjectId.zeroId(), commitId, patchSetId.toRefName());
    ctx.addRefUpdate(cmd);
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand)

Example 5 with ReceiveCommand

use of org.eclipse.jgit.transport.ReceiveCommand 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)

Aggregations

ReceiveCommand (org.eclipse.jgit.transport.ReceiveCommand)82 IOException (java.io.IOException)29 ArrayList (java.util.ArrayList)23 ObjectId (org.eclipse.jgit.lib.ObjectId)23 BatchRefUpdate (org.eclipse.jgit.lib.BatchRefUpdate)22 RevWalk (org.eclipse.jgit.revwalk.RevWalk)21 Repository (org.eclipse.jgit.lib.Repository)19 Ref (org.eclipse.jgit.lib.Ref)18 Test (org.junit.Test)16 RepositoryModel (com.gitblit.models.RepositoryModel)13 Map (java.util.Map)13 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)10 StorageException (com.google.gerrit.exceptions.StorageException)9 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)9 PersonIdent (org.eclipse.jgit.lib.PersonIdent)9 RevCommit (org.eclipse.jgit.revwalk.RevCommit)9 AuthException (com.google.gerrit.extensions.restapi.AuthException)8 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)8 Collection (java.util.Collection)8