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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/*
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */
package Apache.CLI;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Main entry-point into the library.
 *
 * <BR /><BR />Options represents a collection of {@link Option} objects, which describe the
 * possible options for a command-line.
 *
 * <BR /><BR />It may flexibly parse long and short options, with or without values. Additionally,
 * it may parse only a portion of a commandline, allowing for flexible multi-stage parsing.
 *
 * @see Apache.CLI.CommandLine
 */
@Torello.JavaDoc.JDHeaderBackgroundImg(EmbedTagFileID="LICENSE")
public class Options implements Serializable
{
    // The serial version UID.
    private static final long serialVersionUID = 1L;

    // A map of the options with the character key
    private final Map<String, Option> shortOpts = new LinkedHashMap<>();

    // A map of the options with the long key
    private final Map<String, Option> longOpts = new LinkedHashMap<>();

    // A map of the required options
    // N.B. This can contain either a String (addOption) or an OptionGroup (addOptionGroup)
    // TODO this seems wrong

    private final List<Object> requiredOpts = new ArrayList<>();

    // A map of the option groups
    private final Map<String, OptionGroup> optionGroups = new LinkedHashMap<>();

    /**
     * Adds an option instance
     * @param opt the option that is to be added
     * @return the resulting Options instance
     */
    public Options addOption(final Option opt)
    {
        final String key = opt.getKey();

        // add it to the long option list
        if (opt.hasLongOpt()) longOpts.put(opt.getLongOpt(), opt);

        // if the option is required add it to the required list
        if (opt.isRequired())
        {
            if (requiredOpts.contains(key)) requiredOpts.remove(requiredOpts.indexOf(key));
            requiredOpts.add(key);
        }

        shortOpts.put(key, opt);

        return this;
    }

    /**
     * Add an option that only contains a short-name.
     *
     * <BR /><BR />It may be specified as requiring an argument.
     *
     * @param opt Short single-character name of the option.
     * @param hasArg flag signalling if an argument is required after this option
     * @param description Self-documenting description
     * @return the resulting Options instance
     */
    public Options addOption(final String opt, final boolean hasArg, final String description)
    {
        addOption(opt, null, hasArg, description);
        return this;
    }

    /**
     * Add an option that only contains a short name.
     *
     * <BR /><BR />The option does not take an argument.
     *
     * @param opt Short single-character name of the option.
     * @param description Self-documenting description
     * @return the resulting Options instance
     */
    public Options addOption(final String opt, final String description)
    {
        addOption(opt, null, false, description);
        return this;
    }

    /**
     * Add an option that contains a short-name and a long-name.
     *
     * <BR /><BR />It may be specified as requiring an argument.
     *
     * @param opt Short single-character name of the option.
     * @param longOpt Long multi-character name of the option.
     * @param hasArg flag signalling if an argument is required after this option
     * @param description Self-documenting description
     * @return the resulting Options instance
     */
    public Options addOption
        (final String opt, final String longOpt, final boolean hasArg, final String description)
    {
        addOption(new Option(opt, longOpt, hasArg, description));
        return this;
    }

    /**
     * Add the specified option group.
     * @param group the OptionGroup that is to be added
     * @return the resulting Options instance
     */
    public Options addOptionGroup(final OptionGroup group)
    {
        if (group.isRequired()) requiredOpts.add(group);

        for (final Option option : group.getOptions())
        {
            // an Option cannot be required if it is in an OptionGroup, either the group is
            // required or nothing is required

            option.setRequired(false);
            addOption(option);

            optionGroups.put(option.getKey(), group);
        }

        return this;
    }

    /**
     * Add an option that contains a short-name and a long-name.
     *
     * <BR /><BR />The added option is set as required. It may be specified as requiring an
     * argument. This method is a shortcut for:
     *
     * <DIV CLASS=EXAMPLE>{@code
     * Options option = new Option(opt, longOpt, hasArg, description);
     * option.setRequired(true);
     * options.add(option);
     * }</DIV>
     *
     * @param opt Short single-character name of the option.
     * @param longOpt Long multi-character name of the option.
     * @param hasArg flag signalling if an argument is required after this option
     * @param description Self-documenting description
     * @return the resulting Options instance
     */
    public Options addRequiredOption(
            final String opt,
            final String longOpt,
            final boolean hasArg,
            final String description
        )
    {
        final Option option = new Option(opt, longOpt, hasArg, description);
        option.setRequired(true);
        addOption(option);
        return this;
    }

    /**
     * Gets the options with a long name starting with the name specified.
     * @param opt the partial name of the option
     * @return the options matching the partial name specified, or an empty list if none matches
     */
    public List<String> getMatchingOptions(String opt)
    {
        opt = Util.stripLeadingHyphens(opt);

        final List<String> matchingOpts = new ArrayList<>();

        // for a perfect match return the single option only
        if (longOpts.containsKey(opt)) return Collections.singletonList(opt);

        for (final String longOpt : longOpts.keySet())
            if (longOpt.startsWith(opt))
                matchingOpts.add(longOpt);

        return matchingOpts;
    }

    /**
     * Gets the {@link Option} matching the long or short name specified.
     *
     * <BR /><BR />The leading hyphens in the name are ignored (up to 2).
     *
     * @param opt short or long name of the {@link Option}
     * @return the option represented by opt
     */
    public Option getOption(String opt)
    {
        opt = Util.stripLeadingHyphens(opt);

        final Option option = shortOpts.get(opt);

        return option != null ? option : longOpts.get(opt);
    }

    /**
     * Gets the OptionGroup the {@code opt} belongs to.
     * @param opt the option whose OptionGroup is being queried.
     * @return the OptionGroup if {@code opt} is part of an OptionGroup, otherwise return null
     */
    public OptionGroup getOptionGroup(final Option opt)
    { return optionGroups.get(opt.getKey()); }

    /**
     * Gets the OptionGroups that are members of this Options instance.
     * @return a Collection of OptionGroup instances.
     */
    Collection<OptionGroup> getOptionGroups()
    { return new HashSet<>(optionGroups.values()); }

    /**
     * Gets a read-only list of options in this set
     * @return read-only Collection of {@link Option} objects in this descriptor
     */
    public Collection<Option> getOptions()
    { return Collections.unmodifiableCollection(helpOptions()); }

    /**
     * Gets the required options.
     * @return read-only List of required options
     */
    @SuppressWarnings("rawtypes")
    public List getRequiredOptions()
    { return Collections.unmodifiableList(requiredOpts); }

    /**
     * Returns whether the named {@link Option} is a member of this {@link Options}.
     * @param opt long name of the {@link Option}
     * @return true if the named {@link Option} is a member of this {@link Options}
     */
    public boolean hasLongOption(String opt)
    {
        opt = Util.stripLeadingHyphens(opt);
        return longOpts.containsKey(opt);
    }

    /**
     * Returns whether the named {@link Option} is a member of this {@link Options}.
     * @param opt short or long name of the {@link Option}
     * @return true if the named {@link Option} is a member of this {@link Options}
     */
    public boolean hasOption(String opt)
    {
        opt = Util.stripLeadingHyphens(opt);
        return shortOpts.containsKey(opt) || longOpts.containsKey(opt);
    }

    /**
     * Returns whether the named {@link Option} is a member of this {@link Options}.
     * @param opt short name of the {@link Option}
     * @return true if the named {@link Option} is a member of this {@link Options}
     */
    public boolean hasShortOption(String opt)
    {
        opt = Util.stripLeadingHyphens(opt);
        return shortOpts.containsKey(opt);
    }

    /**
     * Returns the Options for use by the HelpFormatter.
     * @return the List of Options
     */
    List<Option> helpOptions()
    { return new ArrayList<>(shortOpts.values()); }

    /**
     * Dump state, suitable for debugging.
     * @return Stringified form of this object
     */
    @Override
    public String toString()
    {
        final StringBuilder buf = new StringBuilder();

        buf.append("[ Options: [ short ");
        buf.append(shortOpts.toString());
        buf.append(" ] [ long ");
        buf.append(longOpts);
        buf.append(" ]");

        return buf.toString();
    }
}