1/*
2 * Copyright (c) 2005, 2016, 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.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25package build.tools.projectcreator;
26
27class ArgIterator {
28    String[] args;
29    int i;
30    ArgIterator(String[] args) {
31        this.args = args;
32        this.i = 0;
33    }
34    String get() { return args[i]; }
35    boolean hasMore() { return args != null && i  < args.length; }
36    boolean next() { return ++i < args.length; }
37}
38
39abstract class ArgHandler {
40    public abstract void handle(ArgIterator it);
41
42}
43
44class ArgRule {
45    String arg;
46    ArgHandler handler;
47    ArgRule(String arg, ArgHandler handler) {
48        this.arg = arg;
49        this.handler = handler;
50    }
51
52    boolean process(ArgIterator it) {
53        if (match(it.get(), arg)) {
54            handler.handle(it);
55            return true;
56        }
57        return false;
58    }
59    boolean match(String rule_pattern, String arg) {
60        return arg.equals(rule_pattern);
61    }
62}
63
64class ArgsParser {
65    ArgsParser(String[] args,
66               ArgRule[] rules,
67               ArgHandler defaulter) {
68        ArgIterator ai = new ArgIterator(args);
69        while (ai.hasMore()) {
70            boolean processed = false;
71            for (int i=0; i<rules.length; i++) {
72                processed |= rules[i].process(ai);
73                if (processed) {
74                    break;
75                }
76            }
77            if (!processed) {
78                if (defaulter != null) {
79                    defaulter.handle(ai);
80                } else {
81                    System.err.println("ERROR: unparsed \""+ai.get()+"\"");
82                    ai.next();
83                }
84            }
85        }
86    }
87}
88