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