Search in sources :

Example 1 with CmdLineParser

use of com.google.gerrit.util.cli.CmdLineParser in project gerrit by GerritCodeReview.

the class ParameterParser method parse.

<T> boolean parse(T param, ListMultimap<String, String> in, HttpServletRequest req, HttpServletResponse res) throws IOException {
    CmdLineParser clp = parserFactory.create(param);
    DynamicOptions pluginOptions = new DynamicOptions(param, injector, dynamicBeans);
    pluginOptions.parseDynamicBeans(clp);
    pluginOptions.setDynamicBeans();
    pluginOptions.onBeanParseStart();
    try {
        clp.parseOptionMap(in);
    } catch (CmdLineException | NumberFormatException e) {
        if (!clp.wasHelpRequestedByOption()) {
            replyError(req, res, SC_BAD_REQUEST, e.getMessage(), e);
            return false;
        }
    }
    if (clp.wasHelpRequestedByOption()) {
        StringWriter msg = new StringWriter();
        clp.printQueryStringUsage(req.getRequestURI(), msg);
        msg.write('\n');
        msg.write('\n');
        clp.printUsage(msg, null);
        msg.write('\n');
        CacheHeaders.setNotCacheable(res);
        replyBinaryResult(req, res, BinaryResult.create(msg.toString()).setContentType("text/plain"));
        return false;
    }
    pluginOptions.onBeanParseEnd();
    return true;
}
Also used : DynamicOptions(com.google.gerrit.server.DynamicOptions) CmdLineParser(com.google.gerrit.util.cli.CmdLineParser) StringWriter(java.io.StringWriter) CmdLineException(org.kohsuke.args4j.CmdLineException)

Example 2 with CmdLineParser

use of com.google.gerrit.util.cli.CmdLineParser in project gerrit by GerritCodeReview.

the class ReceiveCommits method parseMagicBranch.

private void parseMagicBranch(ReceiveCommand cmd) {
    // Permit exactly one new change request per push.
    if (magicBranch != null) {
        reject(cmd, "duplicate request");
        return;
    }
    logDebug("Found magic branch {}", cmd.getRefName());
    magicBranch = new MagicBranchInput(user, cmd, labelTypes, notesMigration);
    magicBranch.reviewer.addAll(reviewersFromCommandLine);
    magicBranch.cc.addAll(ccFromCommandLine);
    String ref;
    CmdLineParser clp = optionParserFactory.create(magicBranch);
    magicBranch.clp = clp;
    try {
        ref = magicBranch.parse(clp, repo, rp.getAdvertisedRefs().keySet(), pushOptions);
    } catch (CmdLineException e) {
        if (!clp.wasHelpRequestedByOption()) {
            logDebug("Invalid branch syntax");
            reject(cmd, e.getMessage());
            return;
        }
        // never happen
        ref = null;
    }
    if (clp.wasHelpRequestedByOption()) {
        StringWriter w = new StringWriter();
        w.write("\nHelp for refs/for/branch:\n\n");
        clp.printUsage(w, null);
        addMessage(w.toString());
        reject(cmd, "see help");
        return;
    }
    if (projectControl.getProjectState().isAllUsers() && RefNames.REFS_USERS_SELF.equals(ref)) {
        logDebug("Handling {}", RefNames.REFS_USERS_SELF);
        ref = RefNames.refsUsers(user.getAccountId());
    }
    if (!rp.getAdvertisedRefs().containsKey(ref) && !ref.equals(readHEAD(repo))) {
        logDebug("Ref {} not found", ref);
        if (ref.startsWith(Constants.R_HEADS)) {
            String n = ref.substring(Constants.R_HEADS.length());
            reject(cmd, "branch " + n + " not found");
        } else {
            reject(cmd, ref + " not found");
        }
        return;
    }
    magicBranch.dest = new Branch.NameKey(project.getNameKey(), ref);
    magicBranch.ctl = projectControl.controlForRef(ref);
    if (projectControl.getProject().getState() != com.google.gerrit.extensions.client.ProjectState.ACTIVE) {
        reject(cmd, "project is read only");
        return;
    }
    if (magicBranch.draft) {
        if (!receiveConfig.allowDrafts) {
            errors.put(Error.CODE_REVIEW, ref);
            reject(cmd, "draft workflow is disabled");
            return;
        } else if (projectControl.controlForRef(MagicBranch.NEW_DRAFT_CHANGE + ref).isBlocked(Permission.PUSH)) {
            errors.put(Error.CODE_REVIEW, ref);
            reject(cmd, "cannot upload drafts");
            return;
        }
    }
    if (!magicBranch.ctl.canUpload()) {
        errors.put(Error.CODE_REVIEW, ref);
        reject(cmd, "cannot upload review");
        return;
    }
    if (magicBranch.isPrivate && magicBranch.removePrivate) {
        reject(cmd, "the options 'private' and 'remove-private' are mutually exclusive");
        return;
    }
    if (magicBranch.workInProgress && magicBranch.ready) {
        reject(cmd, "the options 'wip' and 'ready' are mutually exclusive");
        return;
    }
    if (magicBranch.publishComments && magicBranch.noPublishComments) {
        reject(cmd, "the options 'publish-comments' and 'no-publish-comments' are mutually exclusive");
        return;
    }
    if (magicBranch.draft && magicBranch.submit) {
        reject(cmd, "cannot submit draft");
        return;
    }
    if (magicBranch.submit && !projectControl.controlForRef(MagicBranch.NEW_CHANGE + ref).canSubmit(true)) {
        reject(cmd, "submit not allowed");
        return;
    }
    RevWalk walk = rp.getRevWalk();
    RevCommit tip;
    try {
        tip = walk.parseCommit(magicBranch.cmd.getNewId());
        logDebug("Tip of push: {}", tip.name());
    } catch (IOException ex) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        logError("Invalid pack upload; one or more objects weren't sent", ex);
        return;
    }
    String destBranch = magicBranch.dest.get();
    try {
        if (magicBranch.merged) {
            if (magicBranch.draft) {
                reject(cmd, "cannot be draft & merged");
                return;
            }
            if (magicBranch.base != null) {
                reject(cmd, "cannot use merged with base");
                return;
            }
            RevCommit branchTip = readBranchTip(cmd, magicBranch.dest);
            if (branchTip == null) {
                // readBranchTip already rejected cmd.
                return;
            }
            if (!walk.isMergedInto(tip, branchTip)) {
                reject(cmd, "not merged into branch");
                return;
            }
        }
        // if %base or %merged was specified, ignore newChangeForAllNotInTarget.
        if (tip.getParentCount() > 1 || magicBranch.base != null || magicBranch.merged || tip.getParentCount() == 0) {
            logDebug("Forcing newChangeForAllNotInTarget = false");
            newChangeForAllNotInTarget = false;
        }
        if (magicBranch.base != null) {
            logDebug("Handling %base: {}", magicBranch.base);
            magicBranch.baseCommit = Lists.newArrayListWithCapacity(magicBranch.base.size());
            for (ObjectId id : magicBranch.base) {
                try {
                    magicBranch.baseCommit.add(walk.parseCommit(id));
                } catch (IncorrectObjectTypeException notCommit) {
                    reject(cmd, "base must be a commit");
                    return;
                } catch (MissingObjectException e) {
                    reject(cmd, "base not found");
                    return;
                } catch (IOException e) {
                    logWarn(String.format("Project %s cannot read %s", project.getName(), id.name()), e);
                    reject(cmd, "internal server error");
                    return;
                }
            }
        } else if (newChangeForAllNotInTarget) {
            RevCommit branchTip = readBranchTip(cmd, magicBranch.dest);
            if (branchTip == null) {
                // readBranchTip already rejected cmd.
                return;
            }
            magicBranch.baseCommit = Collections.singletonList(branchTip);
            logDebug("Set baseCommit = {}", magicBranch.baseCommit.get(0).name());
        }
    } catch (IOException ex) {
        logWarn(String.format("Error walking to %s in project %s", destBranch, project.getName()), ex);
        reject(cmd, "internal server error");
        return;
    }
    //
    try {
        Ref targetRef = rp.getAdvertisedRefs().get(magicBranch.ctl.getRefName());
        if (targetRef == null || targetRef.getObjectId() == null) {
            // The destination branch does not yet exist. Assume the
            // history being sent for review will start it and thus
            // is "connected" to the branch.
            logDebug("Branch is unborn");
            return;
        }
        RevCommit h = walk.parseCommit(targetRef.getObjectId());
        logDebug("Current branch tip: {}", h.name());
        RevFilter oldRevFilter = walk.getRevFilter();
        try {
            walk.reset();
            walk.setRevFilter(RevFilter.MERGE_BASE);
            walk.markStart(tip);
            walk.markStart(h);
            if (walk.next() == null) {
                reject(magicBranch.cmd, "no common ancestry");
            }
        } finally {
            walk.reset();
            walk.setRevFilter(oldRevFilter);
        }
    } catch (IOException e) {
        magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
        logError("Invalid pack upload; one or more objects weren't sent", e);
    }
}
Also used : CmdLineParser(com.google.gerrit.util.cli.CmdLineParser) ObjectId(org.eclipse.jgit.lib.ObjectId) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Ref(org.eclipse.jgit.lib.Ref) StringWriter(java.io.StringWriter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) CmdLineException(org.kohsuke.args4j.CmdLineException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 3 with CmdLineParser

use of com.google.gerrit.util.cli.CmdLineParser in project gerrit by GerritCodeReview.

the class AbstractProgram method main.

public final int main(final String[] argv) throws Exception {
    final CmdLineParser clp = new CmdLineParser(OptionHandlers.empty(), this);
    try {
        clp.parseArgument(argv);
    } catch (CmdLineException err) {
        if (!clp.wasHelpRequestedByOption()) {
            System.err.println("fatal: " + err.getMessage());
            return 1;
        }
    }
    if (clp.wasHelpRequestedByOption()) {
        StringWriter msg = new StringWriter();
        clp.printDetailedUsage(getName(), msg);
        System.err.println(msg.toString());
        return 1;
    }
    try {
        ProxyUtil.configureHttpProxy();
        return run();
    } catch (Die err) {
        if (showStackTrace) {
            err.printStackTrace();
        } else {
            final Throwable cause = err.getCause();
            final String diemsg = err.getMessage();
            if (cause != null && !cause.getMessage().equals(diemsg)) {
                System.err.println("fatal: " + cause.getMessage().replaceAll("\n", "\nfatal: "));
            }
            System.err.println("fatal: " + diemsg.replaceAll("\n", "\nfatal: "));
        }
        return 128;
    }
}
Also used : Die(com.google.gerrit.common.Die) CmdLineParser(com.google.gerrit.util.cli.CmdLineParser) StringWriter(java.io.StringWriter) CmdLineException(org.kohsuke.args4j.CmdLineException)

Example 4 with CmdLineParser

use of com.google.gerrit.util.cli.CmdLineParser in project gerrit by GerritCodeReview.

the class BaseCommand method parseCommandLine.

/**
   * Parses the command line argument, injecting parsed values into fields.
   *
   * <p>This method must be explicitly invoked to cause a parse.
   *
   * @param options object whose fields declare Option and Argument annotations to describe the
   *     parameters of the command. Usually {@code this}.
   * @throws UnloggedFailure if the command line arguments were invalid.
   * @see Option
   * @see Argument
   */
protected void parseCommandLine(Object options) throws UnloggedFailure {
    final CmdLineParser clp = newCmdLineParser(options);
    DynamicOptions pluginOptions = new DynamicOptions(options, injector, dynamicBeans);
    pluginOptions.parseDynamicBeans(clp);
    pluginOptions.setDynamicBeans();
    pluginOptions.onBeanParseStart();
    try {
        clp.parseArgument(argv);
    } catch (IllegalArgumentException | CmdLineException err) {
        if (!clp.wasHelpRequestedByOption()) {
            throw new UnloggedFailure(1, "fatal: " + err.getMessage());
        }
    }
    if (clp.wasHelpRequestedByOption()) {
        StringWriter msg = new StringWriter();
        clp.printDetailedUsage(commandName, msg);
        msg.write(usage());
        throw new UnloggedFailure(1, msg.toString());
    }
    pluginOptions.onBeanParseEnd();
}
Also used : DynamicOptions(com.google.gerrit.server.DynamicOptions) CmdLineParser(com.google.gerrit.util.cli.CmdLineParser) StringWriter(java.io.StringWriter) CmdLineException(org.kohsuke.args4j.CmdLineException)

Aggregations

CmdLineParser (com.google.gerrit.util.cli.CmdLineParser)4 StringWriter (java.io.StringWriter)4 CmdLineException (org.kohsuke.args4j.CmdLineException)4 DynamicOptions (com.google.gerrit.server.DynamicOptions)2 Die (com.google.gerrit.common.Die)1 Branch (com.google.gerrit.reviewdb.client.Branch)1 MagicBranch (com.google.gerrit.server.util.MagicBranch)1 IOException (java.io.IOException)1 IncorrectObjectTypeException (org.eclipse.jgit.errors.IncorrectObjectTypeException)1 MissingObjectException (org.eclipse.jgit.errors.MissingObjectException)1 ObjectId (org.eclipse.jgit.lib.ObjectId)1 Ref (org.eclipse.jgit.lib.Ref)1 RevCommit (org.eclipse.jgit.revwalk.RevCommit)1 RevWalk (org.eclipse.jgit.revwalk.RevWalk)1 RevFilter (org.eclipse.jgit.revwalk.filter.RevFilter)1