1 /*
   2  * Copyright (c) 2015, 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.PrintStream;
  30 import java.io.PrintWriter;
  31 import java.lang.module.ModuleFinder;
  32 import java.lang.module.ModuleDescriptor.Version;
  33 import java.nio.file.Path;
  34 import java.nio.file.Paths;
  35 import java.util.regex.Pattern;
  36 import java.util.regex.PatternSyntaxException;
  37 import static jdk.internal.module.WarnIfResolvedReason.*;
  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.printModuleDescriptor)
  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.printModuleDescriptor)
  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.printModuleDescriptor)
  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.printModuleDescriptor)
  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.printModuleDescriptor)
  92                         throw new BadArgs("error.multiple.main.operations").showUsage(true);
  93                     tool.xflag = true;
  94                 }
  95             },
  96             new Option(false, OptionType.MAIN_OPERATION, "--print-module-descriptor", "-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.printModuleDescriptor = 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 isHidden() { 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 = ModuleFinder.compose(jartool.moduleFinder,
 159                                                                 ModuleFinder.of(paths));
 160                 }
 161             },
 162             new Option(false, OptionType.CREATE_UPDATE_INDEX, "--no-compress", "-0") {
 163                 void process(Main jartool, String opt, String arg) {
 164                     jartool.flag0 = true;
 165                 }
 166             },
 167 
 168             // Hidden options
 169             new Option(false, OptionType.OTHER, "-P") {
 170                 void process(Main jartool, String opt, String arg) {
 171                     jartool.pflag = true;
 172                 }
 173                 boolean isHidden() { return true; }
 174             },
 175             new Option(false, OptionType.CREATE_UPDATE, "--do-not-resolve-by-default") {
 176                 void process(Main jartool, String opt, String arg) {
 177                     jartool.doNotResolveByDefault = true;
 178                 }
 179                 boolean isHidden() { return true; }
 180             },
 181             new Option(true, OptionType.CREATE_UPDATE, "--warn-if-resolved") {
 182                 void process(Main jartool, String opt, String arg) throws BadArgs {
 183                     if (arg.equals("deprecated"))
 184                         jartool.warnIfResolvedReason = DEPRECATED;
 185                     else if (arg.equals("deprecated-for-removal"))
 186                         jartool.warnIfResolvedReason = DEPRECATED_FOR_REMOVAL;
 187                     else if (arg.equals("incubating"))
 188                         jartool.warnIfResolvedReason = INCUBATING;
 189                     else
 190                         throw new BadArgs("err.bad.reason", arg).showUsage(true);
 191                 }
 192                 boolean isHidden() { return true; }
 193             },
 194 
 195             // Other options
 196             new Option(true, true, OptionType.OTHER, "--help", "-h") {
 197                 void process(Main jartool, String opt, String arg) throws BadArgs {
 198                     if (jartool.info == null) {
 199                         if (arg == null) {
 200                             jartool.info = Main.Info.HELP;
 201                             return;
 202                         }
 203 
 204                         if (!arg.equals("compat"))
 205                             throw new BadArgs("error.illegal.option", arg).showUsage(true);
 206 
 207                         jartool.info = Main.Info.COMPAT_HELP;
 208                     }
 209                 }
 210             },
 211             new Option(false, OptionType.OTHER, "--version") {
 212                 void process(Main jartool, String opt, String arg) {
 213                     if (jartool.info == null)
 214                         jartool.info = Main.Info.VERSION;
 215                 }
 216             }
 217     };
 218 
 219     enum OptionType {
 220         MAIN_OPERATION("main"),
 221         ANY("any"),
 222         CREATE("create"),
 223         CREATE_UPDATE("create.update"),
 224         CREATE_UPDATE_INDEX("create.update.index"),
 225         OTHER("other");
 226 
 227         /** Resource lookup section prefix. */
 228         final String name;
 229 
 230         OptionType(String name) { this.name = name; }
 231     }
 232 
 233     static abstract class Option {
 234         final boolean hasArg;
 235         final boolean argIsOptional;
 236         final String[] aliases;
 237         final OptionType type;
 238 
 239         Option(boolean hasArg, OptionType type, String... aliases) {
 240             this(hasArg, false, type, aliases);
 241         }
 242 
 243         Option(boolean hasArg, boolean argIsOptional, OptionType type, String... aliases) {
 244             this.hasArg = hasArg;
 245             this.argIsOptional = argIsOptional;
 246             this.type = type;
 247             this.aliases = aliases;
 248         }
 249 
 250         boolean isHidden() { return false; }
 251 
 252         boolean matches(String opt) {
 253             for (String a : aliases) {
 254                 if (a.equals(opt)) {
 255                     return true;
 256                 } else if (opt.startsWith("--") && hasArg && opt.startsWith(a + "=")) {
 257                     return true;
 258                 } else if (opt.startsWith("--help") && opt.startsWith(a + ":")) {
 259                     return true;
 260                 }
 261             }
 262             return false;
 263         }
 264 
 265         abstract void process(Main jartool, String opt, String arg) throws BadArgs;
 266     }
 267 
 268     static int parseOptions(Main jartool, String[] args) throws BadArgs {
 269         int count = 0;
 270         if (args.length == 0) {
 271             jartool.info = Main.Info.USAGE_SUMMARY;
 272             return 0;
 273         }
 274 
 275         // process options
 276         for (; count < args.length; count++) {
 277             if (args[count].charAt(0) != '-' || args[count].equals("-C")
 278                 || args[count].equals("--release"))
 279                 break;
 280 
 281             String name = args[count];
 282             Option option = getOption(name);
 283             String param = null;
 284             if (option.hasArg) {
 285                 if (name.startsWith("--help")) {  // "special" optional separator
 286                     if (name.indexOf(':') > 0) {
 287                         param = name.substring(name.indexOf(':') + 1, name.length());
 288                     }
 289                 } else if (name.startsWith("--") && name.indexOf('=') > 0) {
 290                     param = name.substring(name.indexOf('=') + 1, name.length());
 291                 } else if (count + 1 < args.length) {
 292                     param = args[++count];
 293                 }
 294                 if (!option.argIsOptional &&
 295                     (param == null || param.isEmpty() || param.charAt(0) == '-')) {
 296                     throw new BadArgs("error.missing.arg", name).showUsage(true);
 297                 }
 298             }
 299             option.process(jartool, name, param);
 300         }
 301 
 302         return count;
 303     }
 304 
 305     private static Option getOption(String name) throws BadArgs {
 306         for (Option o : recognizedOptions) {
 307             if (o.matches(name)) {
 308                 return o;
 309             }
 310         }
 311         throw new BadArgs("error.unrecognized.option", name).showUsage(true);
 312     }
 313 
 314     static void printHelp(PrintWriter out) {
 315         out.format("%s%n", Main.getMsg("main.help.preopt"));
 316         for (OptionType type : OptionType.values()) {
 317             boolean typeHeadingWritten = false;
 318 
 319             for (Option o : recognizedOptions) {
 320                 if (!o.type.equals(type))
 321                     continue;
 322                 String name = o.aliases[0].substring(1); // there must always be at least one name
 323                 name = name.charAt(0) == '-' ? name.substring(1) : name;
 324                 if (o.isHidden() || name.equals("h")) {
 325                     continue;
 326                 }
 327                 if (!typeHeadingWritten) {
 328                     out.format("%n%s%n", Main.getMsg("main.help.opt." + type.name));
 329                     typeHeadingWritten = true;
 330                 }
 331                 out.format("%s%n", Main.getMsg("main.help.opt." + type.name + "." + name));
 332             }
 333         }
 334         out.format("%n%s%n%n", Main.getMsg("main.help.postopt"));
 335     }
 336 
 337     static void printCompatHelp(PrintWriter out) {
 338         out.format("%s%n", Main.getMsg("usage.compat"));
 339     }
 340 
 341     static void printUsageSummary(PrintWriter out) {
 342         out.format("%s%n", Main.getMsg("main.usage.summary"));
 343         out.format("%s%n", Main.getMsg("main.usage.summary.try"));
 344     }
 345 
 346     static void printVersion(PrintWriter out) {
 347         out.format("%s %s%n", "jar", System.getProperty("java.version"));
 348     }
 349 }