aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/system/CommandLineParser.java
blob: aedd704756736b1995a31c0f0c3b50770fd56b4e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.system;

import java.util.*;

/**
 * Simple command line parser, handling multiple arguments and multiple unary and binary switches starting with -.
 *
 * Terms used:
 *
 * progname -binaryswitch foo -unaryswitch argument1 argument2
 *
 * @author vegardh
 */
public class CommandLineParser {

    private static final HashSet<String> helpSwitches = new HashSet<>();

    private final List<String> inputStrings;
    private final Map<String, String> legalUnarySwitches = new HashMap<>();
    private final Map<String, String> legalBinarySwitches = new HashMap<>();
    private final List<String> unarySwitches = new ArrayList<>();
    private final Map<String, String> binarySwitches = new HashMap<>();
    private final List<String> arguments = new ArrayList<>();
    private final Map<String, String> requiredUnarySwitches = new HashMap<>();
    private final Map<String, String> requiredBinarySwitches = new HashMap<>();
    private String progname = "progname";
    private String argumentExplanation;
    private int minArguments = 0;
    private int maxArguments = Integer.MAX_VALUE;
    private String helpText;
    private boolean helpSwitchUsed = false;

    static {
        helpSwitches.add("-h");
        helpSwitches.add("-help");
        helpSwitches.add("--help");
        helpSwitches.add("-?");
    }

    public CommandLineParser(String[] cmds) {
        inputStrings = Arrays.asList(cmds);
    }

    public CommandLineParser(String progname, String[] cmds) {
        this.progname=progname;
        inputStrings = Arrays.asList(cmds);
    }

    /**
     * Parses the command line
     * @throws IllegalArgumentException if a parse error occured
     */
    public void parse() {
        for (Iterator<String> it = inputStrings.iterator() ; it.hasNext() ; ) {
            String i = it.next();
            if (isHelpSwitch(i)) {
                helpSwitchUsed = true;
                usageAndThrow();
            }
            if (i.startsWith("-")) {
                if (!isLegalSwitch(i)) {
                    usageAndThrow();
                } else if (legalUnarySwitches.keySet().contains(i)) {
                    unarySwitches.add(i);
                } else if (legalBinarySwitches.keySet().contains(i)) {
                    if (!it.hasNext()) {
                        throw new IllegalArgumentException(i+ " requires value");
                    } else {
                        String val = it.next();
                        binarySwitches.put(i, val);
                    }
                }
            } else {
                arguments.add(i);
            }
        }
        if (!requiredUnarySwitches.isEmpty() && !getUnarySwitches().containsAll(requiredUnarySwitches.keySet())) {
            usageAndThrow();
        }
        if (!requiredBinarySwitches.isEmpty() && !getBinarySwitches().keySet().containsAll(requiredBinarySwitches.keySet())) {
            usageAndThrow();
        }
        if (getArguments().size()<minArguments || getArguments().size()>maxArguments) {
            usageAndThrow();
        }
    }

    private boolean isHelpSwitch(String i) {
        return helpSwitches.contains(i);
    }

    void usageAndThrow() {
        StringBuffer error_sb = new StringBuffer();
        error_sb.append("\nusage: ").append(progname).append(" ");
        if (argumentExplanation!=null) {
            error_sb.append(argumentExplanation);
        }
        if (!legalUnarySwitches.isEmpty()) error_sb.append("\nSwitches:\n");
        error_sb.append("-h This help text\n");
        for (Map.Entry<String, String> e : legalUnarySwitches.entrySet()) {
            error_sb.append(e.getKey()).append(" ").append(e.getValue()).append("\n");
        }
        for (Map.Entry<String, String> e : legalBinarySwitches.entrySet()) {
            error_sb.append(e.getKey()).append(" <").append(e.getValue()).append(">\n");
        }
        if (helpText!=null) {
            error_sb.append("\n").append(helpText).append("\n");
        }
        throw new IllegalArgumentException(error_sb.toString());
    }

    private boolean isLegalSwitch(String s) {
        return (legalUnarySwitches.containsKey(s) || legalBinarySwitches.containsKey(s));
    }

    /**
     * Add a legal unary switch such as "-d"
     */
    public void addLegalUnarySwitch(String s, String explanation) {
        if (legalBinarySwitches.containsKey(s)) {
            throw new IllegalArgumentException(s +" already added as a binary switch");
        }
        legalUnarySwitches.put(s, explanation);
    }

    public void addLegalUnarySwitch(String s) {
        addLegalUnarySwitch(s, null);
    }

    /**
     * Adds a required switch, such as -p
     */
    public void addRequiredUnarySwitch(String s, String explanation) {
        addLegalUnarySwitch(s, explanation);
        requiredUnarySwitches.put(s, explanation);
    }

    /**
     * Add a legal binary switch such as "-f /foo/bar"
     */
    public void addLegalBinarySwitch(String s, String explanation) {
        if (legalUnarySwitches.containsKey(s)) {
            throw new IllegalArgumentException(s +" already added as a unary switch");
        }
        legalBinarySwitches.put(s, explanation);
    }

    /**
     * Adds a legal binary switch without explanation
     */
    public void addLegalBinarySwitch(String s) {
        addLegalBinarySwitch(s, null);
    }

    /**
     * Adds a required binary switch
     */
    public void addRequiredBinarySwitch(String s, String explanation) {
        addLegalBinarySwitch(s, explanation);
        requiredBinarySwitches.put(s, explanation);
    }

    /**
     * The unary switches that were given on the command line
     */
    public List<String> getUnarySwitches() {
        return unarySwitches;
    }

    /**
     * The binary switches that were given on the command line
     */
    public Map<String, String> getBinarySwitches() {
        return binarySwitches;
    }

    /**
     * All non-switch strings that were given on the command line
     */
    public List<String> getArguments() {
        return arguments;
    }

    /**
     * Sets the argument explanation used in printing method, i.e. "names,..."
     */
    public void setArgumentExplanation(String argumentExplanation) {
        this.argumentExplanation = argumentExplanation;
    }

    public void setExtendedHelpText(String text) {
        this.helpText=text;
    }

    public String getHelpText() {
        return helpText;
    }

    /**
     * Sets minimum number of required arguments
     */
    public void setMinArguments(int minArguments) {
        this.minArguments = minArguments;
    }

    /**
     * Sets the maximum number of allowed arguments
     */
    public void setMaxArguments(int maxArguments) {
        this.maxArguments = maxArguments;
    }

    public boolean helpSwitchUsed() {
        return helpSwitchUsed;
    }

}