1 /*
   2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.tools.jar;
  27 
  28 import java.io.File;
  29 import java.io.PrintWriter;
  30 import java.lang.module.ModuleDescriptor.Version;
  31 import java.nio.file.FileSystems;
  32 import java.nio.file.Path;
  33 import java.nio.file.Paths;
  34 import java.util.regex.Pattern;
  35 import java.util.regex.PatternSyntaxException;
  36 import jdk.internal.module.ModulePath;
  37 import jdk.internal.module.ModuleResolution;
  38 
  39 /**
  40  * Parser for GNU Style Options.
  41  */
  42 class GNUStyleOptions {
  43 
  44     static class BadArgs extends Exception {
  45         static final long serialVersionUID = 0L;
  46 
  47         boolean showUsage;
  48 
  49         BadArgs(String key, String arg) { super(Main.formatMsg(key, arg)); }
  50         BadArgs(String key) { super(Main.getMsg(key)); }
  51 
  52         BadArgs showUsage(boolean b) {
  53             showUsage = b;
  54             return this;
  55         }
  56     }
  57 
  58     static Option[] recognizedOptions = {
  59             // Main operations
  60             new Option(false, OptionType.MAIN_OPERATION, "--create", "-c") {
  61                 void process(Main tool, String opt, String arg) throws BadArgs {
  62                     if (tool.iflag || tool.tflag || tool.uflag || tool.xflag || tool.dflag)
  63                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
  64                     tool.cflag = true;
  65                 }
  66             },
  67             new Option(true, OptionType.MAIN_OPERATION, "--generate-index", "-i") {
  68                 void process(Main tool, String opt, String arg) throws BadArgs {
  69                     if (tool.cflag || tool.tflag || tool.uflag || tool.xflag || tool.dflag)
  70                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
  71                     tool.iflag = true;
  72                     tool.rootjar = arg;
  73                 }
  74             },
  75             new Option(false, OptionType.MAIN_OPERATION, "--list", "-t") {
  76                 void process(Main tool, String opt, String arg) throws BadArgs {
  77                     if (tool.cflag || tool.iflag || tool.uflag || tool.xflag || tool.dflag)
  78                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
  79                     tool.tflag = true;
  80                 }
  81             },
  82             new Option(false, OptionType.MAIN_OPERATION, "--update", "-u") {
  83                 void process(Main tool, String opt, String arg) throws BadArgs {
  84                     if (tool.cflag || tool.iflag || tool.tflag || tool.xflag || tool.dflag)
  85                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
  86                     tool.uflag = true;
  87                 }
  88             },
  89             new Option(false, OptionType.MAIN_OPERATION, "--extract", "-x") {
  90                 void process(Main tool, String opt, String arg) throws BadArgs {
  91                     if (tool.cflag || tool.iflag  || tool.tflag || tool.uflag || tool.dflag)
  92                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
  93                     tool.xflag = true;
  94                 }
  95             },
  96             new Option(false, OptionType.MAIN_OPERATION, "--describe-module", "-d") {
  97                 void process(Main tool, String opt, String arg) throws BadArgs {
  98                     if (tool.cflag || tool.iflag  || tool.tflag || tool.uflag || tool.xflag)
  99                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
 100                     tool.dflag = true;
 101                 }
 102             },
 103 
 104             // Additional options
 105             new Option(true, OptionType.ANY, "--file", "-f") {
 106                 void process(Main jartool, String opt, String arg) {
 107                     jartool.fname = arg;
 108                 }
 109             },
 110             new Option(false, OptionType.ANY, "--verbose", "-v") {
 111                 void process(Main jartool, String opt, String arg) {
 112                     jartool.vflag = true;
 113                 }
 114             },
 115             new Option(false, OptionType.CREATE, "--normalize", "-n") {
 116                 void process(Main jartool, String opt, String arg) {
 117                     jartool.nflag = true;
 118                 }
 119                 boolean isExtra() { return true; }
 120             },
 121             new Option(true, OptionType.CREATE_UPDATE, "--main-class", "-e") {
 122                 void process(Main jartool, String opt, String arg) {
 123                     jartool.ename = arg;
 124                 }
 125             },
 126             new Option(true, OptionType.CREATE_UPDATE, "--manifest", "-m") {
 127                 void process(Main jartool, String opt, String arg) {
 128                     jartool.mname = arg;
 129                 }
 130             },
 131             new Option(false, OptionType.CREATE_UPDATE, "--no-manifest", "-M") {
 132                 void process(Main jartool, String opt, String arg) {
 133                     jartool.Mflag = true;
 134                 }
 135             },
 136             new Option(true, OptionType.CREATE_UPDATE, "--module-version") {
 137                 void process(Main jartool, String opt, String arg) {
 138                     jartool.moduleVersion = Version.parse(arg);
 139                 }
 140             },
 141             new Option(true, OptionType.CREATE_UPDATE, "--hash-modules") {
 142                 void process(Main jartool, String opt, String arg) throws BadArgs {
 143                     try {
 144                         jartool.modulesToHash = Pattern.compile(arg);
 145                     } catch (PatternSyntaxException e) {
 146                         throw new BadArgs("err.badpattern", arg).showUsage(true);
 147                     }
 148                 }
 149             },
 150             new Option(true, OptionType.CREATE_UPDATE, "--module-path", "-p") {
 151                 void process(Main jartool, String opt, String arg) {
 152                     String[] dirs = arg.split(File.pathSeparator);
 153                     Path[] paths = new Path[dirs.length];
 154                     int i = 0;
 155                     for (String dir : dirs) {
 156                         paths[i++] = Paths.get(dir);
 157                     }
 158                     jartool.moduleFinder = ModulePath.of(Runtime.version(), true, paths);
 159                 }
 160             },
 161             new Option(false, OptionType.CREATE_UPDATE, "--do-not-resolve-by-default") {
 162                 void process(Main jartool, String opt, String arg) {
 163                     ModuleResolution mres = jartool.moduleResolution;
 164                     jartool.moduleResolution = mres.withDoNotResolveByDefault();
 165                 }
 166                 boolean isExtra() { return true; }
 167             },
 168             new Option(true, OptionType.CREATE_UPDATE, "--warn-if-resolved") {
 169                 void process(Main jartool, String opt, String arg) throws BadArgs {
 170                     ModuleResolution mres = ModuleResolution.empty();
 171                     if (jartool.moduleResolution.doNotResolveByDefault()) {
 172                         mres.withDoNotResolveByDefault();
 173                     }
 174                     if (arg.equals("deprecated")) {
 175                         jartool.moduleResolution = mres.withDeprecated();
 176                     } else if (arg.equals("deprecated-for-removal")) {
 177                         jartool.moduleResolution = mres.withDeprecatedForRemoval();
 178                     } else if (arg.equals("incubating")) {
 179                         jartool.moduleResolution = mres.withIncubating();
 180                     } else {
 181                         throw new BadArgs("error.bad.reason", arg);
 182                     }
 183                 }
 184                 boolean isExtra() { return true; }
 185             },
 186             new Option(false, OptionType.CREATE_UPDATE_INDEX, "--no-compress", "-0") {
 187                 void process(Main jartool, String opt, String arg) {
 188                     jartool.flag0 = true;
 189                 }
 190             },
 191             new Option(true, OptionType.ANY, "--preserve-posix", "-o") {
 192                 void process(Main jartool, String opt, String arg) {
 193                     jartool.oflag = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
 194                 }
 195             },
 196 
 197             // Hidden options
 198             new Option(false, OptionType.OTHER, "-P") {
 199                 void process(Main jartool, String opt, String arg) {
 200                     jartool.pflag = true;
 201                 }
 202                 boolean isHidden() { return true; }
 203             },
 204 
 205             // Other options
 206             new Option(true, true, OptionType.OTHER, "--help", "-h", "-?") {
 207                 void process(Main jartool, String opt, String arg) throws BadArgs {
 208                     if (jartool.info == null) {
 209                         if (arg == null) {
 210                             jartool.info = GNUStyleOptions::printHelp;  //  Main.Info.HELP;
 211                             return;
 212                         }
 213                         if (!arg.equals("compat"))
 214                             throw new BadArgs("error.illegal.option", arg).showUsage(true);
 215                         // jartool.info = Main.Info.COMPAT_HELP;
 216                         jartool.info = GNUStyleOptions::printCompatHelp;
 217                     }
 218                 }
 219             },
 220             new Option(false, OptionType.OTHER, "--help-extra") {
 221                 void process(Main jartool, String opt, String arg) throws BadArgs {
 222                     jartool.info = GNUStyleOptions::printHelpExtra;
 223                 }
 224             },
 225             new Option(false, OptionType.OTHER, "--version") {
 226                 void process(Main jartool, String opt, String arg) {
 227                     if (jartool.info == null)
 228                         jartool.info = GNUStyleOptions::printVersion;
 229                 }
 230             }
 231     };
 232 
 233     enum OptionType {
 234         MAIN_OPERATION("main"),
 235         ANY("any"),
 236         CREATE("create"),
 237         CREATE_UPDATE("create.update"),
 238         CREATE_UPDATE_INDEX("create.update.index"),
 239         OTHER("other");
 240 
 241         /** Resource lookup section prefix. */
 242         final String name;
 243 
 244         OptionType(String name) { this.name = name; }
 245     }
 246 
 247     static abstract class Option {
 248         final boolean hasArg;
 249         final boolean argIsOptional;
 250         final String[] aliases;
 251         final OptionType type;
 252 
 253         Option(boolean hasArg, OptionType type, String... aliases) {
 254             this(hasArg, false, type, aliases);
 255         }
 256 
 257         Option(boolean hasArg, boolean argIsOptional, OptionType type, String... aliases) {
 258             this.hasArg = hasArg;
 259             this.argIsOptional = argIsOptional;
 260             this.type = type;
 261             this.aliases = aliases;
 262         }
 263 
 264         boolean isHidden() { return false; }
 265 
 266         boolean isExtra() { return false; }
 267 
 268         boolean matches(String opt) {
 269             for (String a : aliases) {
 270                 if (a.equals(opt)) {
 271                     return true;
 272                 } else if (opt.startsWith("--") && hasArg && opt.startsWith(a + "=")) {
 273                     return true;
 274                 } else if (opt.startsWith("--help") && opt.startsWith(a + ":")) {
 275                     return true;
 276                 }
 277             }
 278             return false;
 279         }
 280 
 281         abstract void process(Main jartool, String opt, String arg) throws BadArgs;
 282     }
 283 
 284     static int parseOptions(Main jartool, String[] args) throws BadArgs {
 285         int count = 0;
 286         if (args.length == 0) {
 287             jartool.info = GNUStyleOptions::printUsageTryHelp;  //  never be here
 288             return 0;
 289         }
 290 
 291         // process options
 292         for (; count < args.length; count++) {
 293             if (args[count].charAt(0) != '-' || args[count].equals("-C") ||
 294                 args[count].equals("--release"))
 295                 break;
 296 
 297             String name = args[count];
 298             if (name.equals("-XDsuppress-tool-removal-message")) {
 299                 jartool.suppressDeprecateMsg = true;
 300                 continue;
 301             }
 302             Option option = getOption(name);
 303             String param = null;
 304             if (option.hasArg) {
 305                 if (name.startsWith("--help")) {  // "special" optional separator
 306                     if (name.indexOf(':') > 0) {
 307                         param = name.substring(name.indexOf(':') + 1, name.length());
 308                     }
 309                 } else if (name.startsWith("--") && name.indexOf('=') > 0) {
 310                     param = name.substring(name.indexOf('=') + 1, name.length());
 311                 } else if (count + 1 < args.length) {
 312                     param = args[++count];
 313                 }
 314                 if (!option.argIsOptional &&
 315                     (param == null || param.isEmpty() || param.charAt(0) == '-')) {
 316                     throw new BadArgs("error.missing.arg", name).showUsage(true);
 317                 }
 318             }
 319             option.process(jartool, name, param);
 320         }
 321 
 322         return count;
 323     }
 324 
 325     private static Option getOption(String name) throws BadArgs {
 326         for (Option o : recognizedOptions) {
 327             if (o.matches(name)) {
 328                 return o;
 329             }
 330         }
 331         throw new BadArgs("error.unrecognized.option", name).showUsage(true);
 332     }
 333 
 334     static void printHelpExtra(PrintWriter out) {
 335         printHelp0(out, true);
 336     }
 337 
 338     static void printHelp(PrintWriter out) {
 339         printHelp0(out, false);
 340     }
 341 
 342     private static void printHelp0(PrintWriter out, boolean printExtra) {
 343         out.format("%s%n", Main.getMsg("main.help.preopt"));
 344         for (OptionType type : OptionType.values()) {
 345             boolean typeHeadingWritten = false;
 346 
 347             for (Option o : recognizedOptions) {
 348                 if (!o.type.equals(type))
 349                     continue;
 350                 String name = o.aliases[0].substring(1); // there must always be at least one name
 351                 name = name.charAt(0) == '-' ? name.substring(1) : name;
 352                 if (o.isHidden() || name.equals("h")) {
 353                     continue;
 354                 }
 355                 if (o.isExtra() && !printExtra) {
 356                     continue;
 357                 }
 358                 if (!typeHeadingWritten) {
 359                     out.format("%n%s%n", Main.getMsg("main.help.opt." + type.name));
 360                     typeHeadingWritten = true;
 361                 }
 362                 out.format("%s%n", Main.getMsg("main.help.opt." + type.name + "." + name));
 363             }
 364         }
 365         out.format("%n%s%n%n", Main.getMsg("main.help.postopt"));
 366     }
 367 
 368     static void printCompatHelp(PrintWriter out) {
 369         out.format("%s%n", Main.getMsg("usage.compat"));
 370     }
 371 
 372     static void printUsageTryHelp(PrintWriter out) {
 373         out.format("%s%n", Main.getMsg("main.usage.summary.try"));
 374     }
 375 
 376     static void printVersion(PrintWriter out) {
 377         out.format("%s %s%n", "jar", System.getProperty("java.version"));
 378     }
 379 }