Example usage for org.eclipse.jgit.transport ReceiveCommand setResult

List of usage examples for org.eclipse.jgit.transport ReceiveCommand setResult

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport ReceiveCommand setResult.

Prototype

public void setResult(Result s, String m) 

Source Link

Document

Set the status of this command.

Usage

From source file:com.gitblit.git.GitblitReceivePack.java

License:Apache License

/**
 * Instrumentation point where the incoming push event has been parsed,
 * validated, objects created BUT refs have not been updated. You might
 * use this to enforce a branch-write permissions model.
 *///  w w w  . j av  a2 s  .co m
@Override
public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {

    if (commands.size() == 0) {
        // no receive commands to process
        // this can happen if receive pack subclasses intercept and filter
        // the commands
        LOGGER.debug("skipping pre-receive processing, no refs created, updated, or removed");
        return;
    }

    if (repository.isMirror) {
        // repository is a mirror
        for (ReceiveCommand cmd : commands) {
            sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is a mirror!",
                    repository.name);
        }
        return;
    }

    if (repository.isFrozen) {
        // repository is frozen/readonly
        for (ReceiveCommand cmd : commands) {
            sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is frozen!",
                    repository.name);
        }
        return;
    }

    if (!repository.isBare) {
        // repository has a working copy
        for (ReceiveCommand cmd : commands) {
            sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it has a working copy!",
                    repository.name);
        }
        return;
    }

    if (!canPush(commands)) {
        // user does not have push permissions
        for (ReceiveCommand cmd : commands) {
            sendRejection(cmd, "User \"{0}\" does not have push permissions for \"{1}\"!", user.username,
                    repository.name);
        }
        return;
    }

    if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) {
        // enforce committer verification
        if (StringUtils.isEmpty(user.emailAddress)) {
            // reject the push because the pushing account does not have an email address
            for (ReceiveCommand cmd : commands) {
                sendRejection(cmd,
                        "Sorry, the account \"{0}\" does not have an email address set for committer verification!",
                        user.username);
            }
            return;
        }

        // Optionally enforce that the committer of first parent chain
        // match the account being used to push the commits.
        //
        // This requires all merge commits are executed with the "--no-ff"
        // option to force a merge commit even if fast-forward is possible.
        // This ensures that the chain first parents has the commit
        // identity of the merging user.
        boolean allRejected = false;
        for (ReceiveCommand cmd : commands) {
            String firstParent = null;
            try {
                List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(),
                        cmd.getNewId().name());
                for (RevCommit commit : commits) {

                    if (firstParent != null) {
                        if (!commit.getName().equals(firstParent)) {
                            // ignore: commit is right-descendant of a merge
                            continue;
                        }
                    }

                    // update expected next commit id
                    if (commit.getParentCount() == 0) {
                        firstParent = null;
                    } else {
                        firstParent = commit.getParents()[0].getId().getName();
                    }

                    PersonIdent committer = commit.getCommitterIdent();
                    if (!user.is(committer.getName(), committer.getEmailAddress())) {
                        // verification failed
                        String reason = MessageFormat.format(
                                "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(),
                                committer.getName(),
                                StringUtils.isEmpty(committer.getEmailAddress()) ? "?"
                                        : committer.getEmailAddress(),
                                user.getDisplayName(), user.username, user.emailAddress);
                        LOGGER.warn(reason);
                        cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
                        allRejected &= true;
                        break;
                    } else {
                        allRejected = false;
                    }
                }
            } catch (Exception e) {
                LOGGER.error("Failed to verify commits were made by pushing user", e);
            }
        }

        if (allRejected) {
            // all ref updates rejected, abort
            return;
        }
    }

    for (ReceiveCommand cmd : commands) {
        String ref = cmd.getRefName();
        if (ref.startsWith(Constants.R_HEADS)) {
            switch (cmd.getType()) {
            case UPDATE_NONFASTFORWARD:
            case DELETE:
                // reset branch commit cache on REWIND and DELETE
                CommitCache.instance().clear(repository.name, ref);
                break;
            default:
                break;
            }
        } else if (ref.equals(BranchTicketService.BRANCH)) {
            // ensure pushing user is an administrator OR an owner
            // i.e. prevent ticket tampering
            boolean permitted = user.canAdmin() || repository.isOwner(user.username);
            if (!permitted) {
                sendRejection(cmd, "{0} is not permitted to push to {1}", user.username, ref);
            }
        } else if (ref.startsWith(Constants.R_FOR)) {
            // prevent accidental push to refs/for
            sendRejection(cmd, "{0} is not configured to receive patchsets", repository.name);
        }
    }

    // call pre-receive plugins
    for (ReceiveHook hook : gitblit.getExtensions(ReceiveHook.class)) {
        try {
            hook.onPreReceive(this, commands);
        } catch (Exception e) {
            LOGGER.error("Failed to execute extension", e);
        }
    }

    Set<String> scripts = new LinkedHashSet<String>();
    scripts.addAll(gitblit.getPreReceiveScriptsInherited(repository));
    if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) {
        scripts.addAll(repository.preReceiveScripts);
    }
    runGroovy(commands, scripts);
    for (ReceiveCommand cmd : commands) {
        if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) {
            LOGGER.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(),
                    cmd.getResult(), cmd.getMessage()));
        }
    }
}

From source file:com.gitblit.git.GitblitReceivePack.java

License:Apache License

public void sendRejection(final ReceiveCommand cmd, final String why, Object... objects) {
    String text;//from ww w. j a  v  a  2  s.  c o  m
    if (ArrayUtils.isEmpty(objects)) {
        text = why;
    } else {
        text = MessageFormat.format(why, objects);
    }
    cmd.setResult(Result.REJECTED_OTHER_REASON, text);
    LOGGER.error(text + " (" + user.username + ")");
}

From source file:com.gitblit.git.ReceiveHook.java

License:Apache License

/**
 * Instrumentation point where the incoming push event has been parsed,
 * validated, objects created BUT refs have not been updated. You might
 * use this to enforce a branch-write permissions model.
 *///w  ww  .j  a v a  2 s. c om
@Override
public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {
    if (repository.isFrozen) {
        // repository is frozen/readonly
        String reason = MessageFormat.format("Gitblit does not allow pushes to \"{0}\" because it is frozen!",
                repository.name);
        logger.warn(reason);
        for (ReceiveCommand cmd : commands) {
            cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
        }
        return;
    }

    if (!repository.isBare) {
        // repository has a working copy
        String reason = MessageFormat.format(
                "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name);
        logger.warn(reason);
        for (ReceiveCommand cmd : commands) {
            cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
        }
        return;
    }

    if (!user.canPush(repository)) {
        // user does not have push permissions
        String reason = MessageFormat.format("User \"{0}\" does not have push permissions for \"{1}\"!",
                user.username, repository.name);
        logger.warn(reason);
        for (ReceiveCommand cmd : commands) {
            cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
        }
        return;
    }

    if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) {
        // enforce committer verification
        if (StringUtils.isEmpty(user.emailAddress)) {
            // emit warning if user does not have an email address 
            logger.warn(MessageFormat.format(
                    "Consider setting an email address for {0} ({1}) to improve committer verification.",
                    user.getDisplayName(), user.username));
        }

        // Optionally enforce that the committer of the left parent chain
        // match the account being used to push the commits.
        // 
        // This requires all merge commits are executed with the "--no-ff"
        // option to force a merge commit even if fast-forward is possible.
        // This ensures that the chain of left parents has the commit
        // identity of the merging user.
        boolean allRejected = false;
        for (ReceiveCommand cmd : commands) {
            String linearParent = null;
            try {
                List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(),
                        cmd.getNewId().name());
                for (RevCommit commit : commits) {

                    if (linearParent != null) {
                        if (!commit.getName().equals(linearParent)) {
                            // ignore: commit is right-descendant of a merge
                            continue;
                        }
                    }

                    // update expected next commit id
                    if (commit.getParentCount() == 0) {
                        linearParent = null;
                    } else {
                        linearParent = commit.getParents()[0].getId().getName();
                    }

                    PersonIdent committer = commit.getCommitterIdent();
                    if (!user.is(committer.getName(), committer.getEmailAddress())) {
                        String reason;
                        if (StringUtils.isEmpty(user.emailAddress)) {
                            // account does not have an email address
                            reason = MessageFormat.format("{0} by {1} <{2}> was not committed by {3} ({4})",
                                    commit.getId().name(), committer.getName(),
                                    StringUtils.isEmpty(committer.getEmailAddress()) ? "?"
                                            : committer.getEmailAddress(),
                                    user.getDisplayName(), user.username);
                        } else {
                            // account has an email address
                            reason = MessageFormat.format(
                                    "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>",
                                    commit.getId().name(), committer.getName(),
                                    StringUtils.isEmpty(committer.getEmailAddress()) ? "?"
                                            : committer.getEmailAddress(),
                                    user.getDisplayName(), user.username, user.emailAddress);
                        }
                        logger.warn(reason);
                        cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
                        allRejected &= true;
                        break;
                    } else {
                        allRejected = false;
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to verify commits were made by pushing user", e);
            }
        }

        if (allRejected) {
            // all ref updates rejected, abort
            return;
        }
    }

    // reset branch commit cache on REWIND and DELETE
    for (ReceiveCommand cmd : commands) {
        String ref = cmd.getRefName();
        if (ref.startsWith(Constants.R_HEADS)) {
            switch (cmd.getType()) {
            case UPDATE_NONFASTFORWARD:
            case DELETE:
                CommitCache.instance().clear(repository.name, ref);
                break;
            default:
                break;
            }
        }
    }

    Set<String> scripts = new LinkedHashSet<String>();
    scripts.addAll(GitBlit.self().getPreReceiveScriptsInherited(repository));
    if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) {
        scripts.addAll(repository.preReceiveScripts);
    }
    runGroovy(repository, user, commands, rp, scripts);
    for (ReceiveCommand cmd : commands) {
        if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) {
            logger.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(),
                    cmd.getResult(), cmd.getMessage()));
        }
    }
}

From source file:com.gitblit.plugin.tbacl.TBACLReceiveHook.java

License:Apache License

@Override
public void onPreReceive(GitblitReceivePack receivePack, Collection<ReceiveCommand> commands) {
    final UserModel user = receivePack.getUserModel();
    final RepositoryModel repository = receivePack.getRepositoryModel();
    final IStoredSettings settings = receivePack.getGitblit().getSettings();

    boolean applyToPersonalRepos = settings.getBoolean(Plugin.SETTING_APPLY_TO_PERSONAL_REPOS, false);
    if (repository.isPersonalRepository() && !applyToPersonalRepos) {
        return;/*from  w w  w.jav  a 2 s.  c  o m*/
    }

    if (user.canAdmin()) {
        log.info("{}: permitting push from administrator '{}'", name, user.username);
        return;
    }

    Version systemVersion = receivePack.getGitblit().getSystemVersion();
    if (systemVersion.atLeast(new Version(1, 6, 0))) {
        if (user.canAdmin(repository)) {
            log.info("{}: permitting push from owner '{}'", name, user.username);
            return;
        }
    } else {
        if (repository.isOwner(user.username) || user.isMyPersonalRepository(repository.name)) {
            log.info("{}: permitting push from owner '{}'", name, user.username);
            return;
        }
    }

    boolean useTeamNamespaces = settings.getBoolean(Plugin.SETTING_USE_TEAM_NAMESPACES, false);
    for (ReceiveCommand cmd : commands) {
        String reject = String.format("%s: Sorry, '%s' does not have permission to push to '%s'", name,
                user.username, cmd.getRefName());

        if (cmd.getRefName().startsWith(Constants.R_HEADS)) {
            // pushing a branch
            String branch = Repository.shortenRefName(cmd.getRefName());
            String team;

            if (useTeamNamespaces) {
                if (branch.indexOf('/') == -1) {
                    // not a team namespace branch
                    String notTeamBranch = String.format(
                            "%s: Sorry, '%s' is not a team branch! e.g. refs/heads/{team}/%s'", name,
                            cmd.getRefName(), branch);
                    log.debug(notTeamBranch);
                    cmd.setResult(Result.REJECTED_OTHER_REASON, notTeamBranch);
                    continue;
                } else {
                    // extract team name from the branch
                    team = branch.substring(0, branch.indexOf('/'));
                }
            } else {
                team = branch;
            }

            // enforce user is member of team named for a branch
            if (!user.isTeamMember(team)) {
                log.debug(reject);
                cmd.setResult(Result.REJECTED_OTHER_REASON, reject);
            } else {
                log.info("{}: permitting push from '{}' to branch '{}'", name, user.username, branch);
            }
        } else {
            // pushing something else
            cmd.setResult(Result.REJECTED_OTHER_REASON, reject);
        }
    }
}

From source file:com.google.gerrit.gpg.SignedPushPreReceiveHook.java

License:Apache License

private static void reject(Collection<ReceiveCommand> commands, String reason) {
    for (ReceiveCommand cmd : commands) {
        if (cmd.getResult() == ReceiveCommand.Result.NOT_ATTEMPTED) {
            cmd.setResult(ReceiveCommand.Result.REJECTED_OTHER_REASON, reason);
        }/*ww  w. j av  a 2 s  .  c  o  m*/
    }
}

From source file:com.google.gerrit.server.git.AsyncReceiveCommits.java

License:Apache License

@Override
public void onPreReceive(final ReceivePack rp, final Collection<ReceiveCommand> commands) {
    try {/* ww w  .java2 s  .  c o  m*/
        progress.waitFor(executor.submit(scopePropagator.wrap(new Worker(commands))), timeoutMillis,
                TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        log.warn(String.format("Error in ReceiveCommits while processing changes for project %s",
                rc.getProject().getName()), e);
        rc.addError("internal error while processing changes");
        // ReceiveCommits has tried its best to catch errors, so anything at this
        // point is very bad.
        for (final ReceiveCommand c : commands) {
            if (c.getResult() == Result.NOT_ATTEMPTED) {
                c.setResult(Result.REJECTED_OTHER_REASON, "internal error");
            }
        }
    } finally {
        rc.sendMessages();
    }
}

From source file:com.google.gerrit.server.git.ReceiveCommits.java

License:Apache License

void processCommands(final Collection<ReceiveCommand> commands, final MultiProgressMonitor progress) {
    newProgress = progress.beginSubTask("new", UNKNOWN);
    replaceProgress = progress.beginSubTask("updated", UNKNOWN);
    closeProgress = progress.beginSubTask("closed", UNKNOWN);
    commandProgress = progress.beginSubTask("refs", UNKNOWN);

    batch = repo.getRefDatabase().newBatchUpdate();
    batch.setPushCertificate(rp.getPushCertificate());
    batch.setRefLogIdent(rp.getRefLogIdent());
    batch.setRefLogMessage("push", true);

    parseCommands(commands);//from  w  w w  . j  a  v  a2  s.co  m
    if (magicBranch != null && magicBranch.cmd.getResult() == NOT_ATTEMPTED) {
        selectNewAndReplacedChangesFromMagicBranch();
    }
    preparePatchSetsForReplace();

    if (!batch.getCommands().isEmpty()) {
        try {
            if (!batch.isAllowNonFastForwards() && magicBranch != null && magicBranch.edit) {
                batch.setAllowNonFastForwards(true);
            }
            batch.execute(rp.getRevWalk(), commandProgress);
        } catch (IOException err) {
            int cnt = 0;
            for (ReceiveCommand cmd : batch.getCommands()) {
                if (cmd.getResult() == NOT_ATTEMPTED) {
                    cmd.setResult(REJECTED_OTHER_REASON, "internal server error");
                    cnt++;
                }
            }
            log.error(String.format("Failed to store %d refs in %s", cnt, project.getName()), err);
        }
    }

    insertChangesAndPatchSets();
    newProgress.end();
    replaceProgress.end();

    if (!errors.isEmpty()) {
        for (Error error : errors.keySet()) {
            rp.sendMessage(buildError(error, errors.get(error)));
        }
        rp.sendMessage(String.format("User: %s", displayName(currentUser)));
        rp.sendMessage(COMMAND_REJECTION_MESSAGE_FOOTER);
    }

    Set<Branch.NameKey> branches = Sets.newHashSet();
    for (final ReceiveCommand c : commands) {
        if (c.getResult() == OK) {
            if (c.getType() == ReceiveCommand.Type.UPDATE) { // aka fast-forward
                tagCache.updateFastForward(project.getNameKey(), c.getRefName(), c.getOldId(), c.getNewId());
            }

            if (isHead(c) || isConfig(c)) {
                switch (c.getType()) {
                case CREATE:
                case UPDATE:
                case UPDATE_NONFASTFORWARD:
                    autoCloseChanges(c);
                    branches.add(new Branch.NameKey(project.getNameKey(), c.getRefName()));
                    break;

                case DELETE:
                    ResultSet<SubmoduleSubscription> submoduleSubscriptions = null;
                    Branch.NameKey projRef = new Branch.NameKey(project.getNameKey(), c.getRefName());
                    try {
                        submoduleSubscriptions = db.submoduleSubscriptions().bySuperProject(projRef);
                        db.submoduleSubscriptions().delete(submoduleSubscriptions);
                    } catch (OrmException e) {
                        log.error("Cannot delete submodule subscription(s) of branch " + projRef + ": "
                                + submoduleSubscriptions, e);
                    }
                    break;
                }
            }

            if (isConfig(c)) {
                projectCache.evict(project);
                ProjectState ps = projectCache.get(project.getNameKey());
                repoManager.setProjectDescription(project.getNameKey(), //
                        ps.getProject().getDescription());
            }

            if (!MagicBranch.isMagicBranch(c.getRefName())) {
                // We only fire gitRefUpdated for direct refs updates.
                // Events for change refs are fired when they are created.
                //
                gitRefUpdated.fire(project.getNameKey(), c);
                hooks.doRefUpdatedHook(new Branch.NameKey(project.getNameKey(), c.getRefName()), c.getOldId(),
                        c.getNewId(), currentUser.getAccount());
            }
        }
    }
    // Update superproject gitlinks if required.
    SubmoduleOp op = subOpProvider.get();
    try {
        op.updateSubmoduleSubscriptions(db, branches);
        op.updateSuperProjects(db, branches);
    } catch (SubmoduleException e) {
        log.error("Can't update submodule subscriptions " + "or update the superprojects", e);
    }

    closeProgress.end();
    commandProgress.end();
    progress.end();
    reportMessages();
}

From source file:com.google.gerrit.server.git.ReceiveCommits.java

License:Apache License

private void parseRewind(final ReceiveCommand cmd) {
    RevCommit newObject;//  w w w  . j a v a2 s.  c  o  m
    try {
        newObject = rp.getRevWalk().parseCommit(cmd.getNewId());
    } catch (IncorrectObjectTypeException notCommit) {
        newObject = null;
    } catch (IOException err) {
        log.error("Invalid object " + cmd.getNewId().name() + " for " + cmd.getRefName() + " forced update",
                err);
        reject(cmd, "invalid object");
        return;
    }

    RefControl ctl = projectControl.controlForRef(cmd.getRefName());
    if (newObject != null) {
        validateNewCommits(ctl, cmd);
        if (cmd.getResult() != NOT_ATTEMPTED) {
            return;
        }
    }

    if (ctl.canForceUpdate()) {
        batch.setAllowNonFastForwards(true).addCommand(cmd);
    } else {
        cmd.setResult(REJECTED_NONFASTFORWARD, " need '" + PermissionRule.FORCE_PUSH + "' privilege.");
    }
}

From source file:com.google.gerrit.server.git.ReceiveCommits.java

License:Apache License

private void reject(final ReceiveCommand cmd, final String why) {
    cmd.setResult(REJECTED_OTHER_REASON, why);
    commandProgress.update(1);//from w  w w  .  jav  a2  s  . c  om
}

From source file:com.google.gerrit.server.project.DeleteBranches.java

License:Apache License

private ReceiveCommand createDeleteCommand(ProjectResource project, Repository r, String branch)
        throws OrmException, IOException {
    Ref ref = r.getRefDatabase().getRef(branch);
    ReceiveCommand command;
    if (ref == null) {
        command = new ReceiveCommand(ObjectId.zeroId(), ObjectId.zeroId(), branch);
        command.setResult(Result.REJECTED_OTHER_REASON,
                "it doesn't exist or you do not have permission to delete it");
        return command;
    }/*from  w w w  . ja  va  2 s.com*/
    command = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());
    Branch.NameKey branchKey = new Branch.NameKey(project.getNameKey(), ref.getName());
    if (!project.getControl().controlForRef(branchKey).canDelete()) {
        command.setResult(Result.REJECTED_OTHER_REASON,
                "it doesn't exist or you do not have permission to delete it");
    }
    if (!queryProvider.get().setLimit(1).byBranchOpen(branchKey).isEmpty()) {
        command.setResult(Result.REJECTED_OTHER_REASON, "it has open changes");
    }
    return command;
}