From 74a8c3e529f0c3ec9ab02db684e9d0ec4f71bf64 Mon Sep 17 00:00:00 2001 From: ccalvarin Date: Fri, 18 Aug 2017 16:21:32 +0200 Subject: Switch android tools' use of options parser to a more concise form for the single options-base case. This is to prepare the options parser from making options parser creation exceptions a caught exception. Since all of these classes already have a single options class and used parseAndExitUponError, this allows us to keep behavior consistent between the malformed options-base errors and the incorrect user-input errors. All the other uses of the options parser in //src/tools already throw sufficiently broad exceptions to not need this. RELNOTES: None PiperOrigin-RevId: 165702786 --- .../com/google/devtools/common/options/Options.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src/main/java/com/google/devtools/common/options/Options.java') diff --git a/src/main/java/com/google/devtools/common/options/Options.java b/src/main/java/com/google/devtools/common/options/Options.java index c52e395ecf..b636c09532 100644 --- a/src/main/java/com/google/devtools/common/options/Options.java +++ b/src/main/java/com/google/devtools/common/options/Options.java @@ -14,6 +14,7 @@ package com.google.devtools.common.options; +import com.google.devtools.common.options.OptionsParser.ConstructionException; import java.util.Arrays; import java.util.List; @@ -55,6 +56,26 @@ public class Options { return new Options<>(parser.getOptions(optionsClass), remainingArgs.toArray(new String[0])); } + /** + * A convenience function for use in main methods. Parses the command line parameters, and exits + * upon error. Also, prints out the usage message if "--help" appears anywhere within {@code + * args}. + */ + public static Options parseAndExitUponError( + Class optionsClass, boolean allowResidue, String... args) { + OptionsParser parser = null; + try { + parser = OptionsParser.newOptionsParser(optionsClass); + parser.setAllowResidue(allowResidue); + } catch (ConstructionException e) { + System.err.println("Error constructing the options parser: " + e.getMessage()); + System.exit(2); + } + parser.parseAndExitUponError(args); + List remainingArgs = parser.getResidue(); + return new Options<>(parser.getOptions(optionsClass), remainingArgs.toArray(new String[0])); + } + /** * Returns an options object at its default values. The returned object may * be freely modified by the caller, by assigning its fields. -- cgit v1.2.3