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

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Get the message associated with a failure status.

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.
 *//*from   w w  w. j  a v a  2s.  c o 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.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 w  w.j  av  a 2s.  com*/
@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.Tests.java

License:Apache License

protected void push(User username, Branch branch, boolean expectSuccess) {

    RepositoryModel repo = new RepositoryModel();
    repo.name = "test.git";
    repo.owners = Arrays.asList(User.owner.name());

    IGitblit gitblit = new MockGitblit();
    gitblit.getSettings().overrideSetting(Plugin.SETTING_USE_TEAM_NAMESPACES, branch.useNamespace());

    try {/*  w  ww.  j  a v a  2s  . c  o m*/
        gitblit.updateRepositoryModel(repo.name, repo, false);
    } catch (GitBlitException e) {
    }

    UserModel user = gitblit.getUserModel(username.name());
    Repository db = gitblit.getRepository(repo.name);

    GitblitReceivePack rp = new GitblitReceivePack(gitblit, db, repo, user);

    ObjectId sha1 = ObjectId.fromString("2d291de884b4bb3164fda516ebc8510f757495b7");
    ObjectId sha2 = ObjectId.fromString("42972d830611fa4b1aa2c2c49c824a15e1987597");

    List<ReceiveCommand> commands = Arrays
            .asList(new ReceiveCommand(sha1, sha2, "refs/heads/" + branch.toString()));

    TBACLReceiveHook hook = new TBACLReceiveHook();
    hook.onPreReceive(rp, commands);

    for (ReceiveCommand cmd : commands) {
        assertEquals(cmd.getMessage(), expectSuccess, Result.NOT_ATTEMPTED == cmd.getResult());
    }
}

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

License:Apache License

public void deleteAllDraftsFromAllUsers(Change.Id changeId) throws IOException {
    try (Repository repo = repoManager.openRepository(allUsers); RevWalk rw = new RevWalk(repo)) {
        BatchRefUpdate bru = repo.getRefDatabase().newBatchUpdate();
        for (Ref ref : getDraftRefs(repo, changeId)) {
            bru.addCommand(new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName()));
        }/* ww  w  .  j  ava2  s  .  co m*/
        bru.setRefLogMessage("Delete drafts from NoteDb", false);
        bru.execute(rw, NullProgressMonitor.INSTANCE);
        for (ReceiveCommand cmd : bru.getCommands()) {
            if (cmd.getResult() != ReceiveCommand.Result.OK) {
                throw new IOException(String.format("Failed to delete draft comment ref %s at %s: %s (%s)",
                        cmd.getRefName(), cmd.getOldId(), cmd.getResult(), cmd.getMessage()));
            }
        }
    }
}

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

License:Apache License

private void appendAndLogErrorMessage(StringBuilder errorMessages, ReceiveCommand cmd) {
    String msg = null;/* www. j  a  v  a 2  s  . com*/
    switch (cmd.getResult()) {
    case REJECTED_CURRENT_BRANCH:
        msg = format("Cannot delete %s: it is the current branch", cmd.getRefName());
        break;
    case REJECTED_OTHER_REASON:
        msg = format("Cannot delete %s: %s", cmd.getRefName(), cmd.getMessage());
        break;
    default:
        msg = format("Cannot delete %s: %s", cmd.getRefName(), cmd.getResult());
        break;
    }
    log.error(msg);
    errorMessages.append(msg);
    errorMessages.append("\n");
}

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

License:Apache License

private void appendAndLogErrorMessage(StringBuilder errorMessages, ReceiveCommand cmd) {
    String msg = null;/*from  w  w w.j  ava  2  s .  c  o m*/
    switch (cmd.getResult()) {
    case REJECTED_CURRENT_BRANCH:
        msg = format("Cannot delete %s: it is the current branch", cmd.getRefName());
        break;
    case REJECTED_OTHER_REASON:
        msg = format("Cannot delete %s: %s", cmd.getRefName(), cmd.getMessage());
        break;
    case LOCK_FAILURE:
    case NOT_ATTEMPTED:
    case OK:
    case REJECTED_MISSING_OBJECT:
    case REJECTED_NOCREATE:
    case REJECTED_NODELETE:
    case REJECTED_NONFASTFORWARD:
    default:
        msg = format("Cannot delete %s: %s", cmd.getRefName(), cmd.getResult());
        break;
    }
    log.error(msg);
    errorMessages.append(msg);
    errorMessages.append("\n");
}