001/*
002  Licensed to the Apache Software Foundation (ASF) under one or more
003  contributor license agreements.  See the NOTICE file distributed with
004  this work for additional information regarding copyright ownership.
005  The ASF licenses this file to You under the Apache License, Version 2.0
006  (the "License"); you may not use this file except in compliance with
007  the License.  You may obtain a copy of the License at
008
009      https://www.apache.org/licenses/LICENSE-2.0
010
011  Unless required by applicable law or agreed to in writing, software
012  distributed under the License is distributed on an "AS IS" BASIS,
013  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  See the License for the specific language governing permissions and
015  limitations under the License.
016 */
017
018package org.apache.commons.cli;
019
020import java.io.Serializable;
021import java.util.ArrayList;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.HashSet;
025import java.util.LinkedHashMap;
026import java.util.List;
027import java.util.Map;
028
029/**
030 * Main entry-point into the library.
031 * <p>
032 * Options represents a collection of {@link Option} objects, which describe the possible options for a command-line.
033 * </p>
034 * <p>
035 * It may flexibly parse long and short options, with or without values. Additionally, it may parse only a portion of a
036 * command-line, allowing for flexible multi-stage parsing.
037 * </p>
038 *
039 * @see org.apache.commons.cli.CommandLine
040 */
041public class Options implements Serializable {
042
043    /** The serial version UID. */
044    private static final long serialVersionUID = 1L;
045
046    /** A map of the options with the character key */
047    private final Map<String, Option> shortOpts = new LinkedHashMap<>();
048
049    /** A map of the options with the long key */
050    private final Map<String, Option> longOpts = new LinkedHashMap<>();
051
052    /** A map of the required options */
053    // This can contain either a String (addOption) or an OptionGroup (addOptionGroup)
054    // TODO this seems wrong
055    private final List<Object> requiredOpts = new ArrayList<>();
056
057    /** A map of the option groups */
058    private final Map<String, OptionGroup> optionGroups = new LinkedHashMap<>();
059
060    /**
061     * Constructs new instance.
062     */
063    public Options() {
064        // empty
065    }
066
067    /**
068     * Adds an option instance.
069     *
070     * @param opt the option that is to be added.
071     * @return the resulting Options instance.
072     */
073    public Options addOption(final Option opt) {
074        final String key = opt.getKey();
075        // add it to the long option list
076        if (opt.hasLongOpt()) {
077            longOpts.put(opt.getLongOpt(), opt);
078        }
079        // if the option is required add it to the required list
080        if (opt.isRequired()) {
081            if (requiredOpts.contains(key)) {
082                requiredOpts.remove(requiredOpts.indexOf(key));
083            }
084            requiredOpts.add(key);
085        }
086        shortOpts.put(key, opt);
087        return this;
088    }
089
090    /**
091     * Adds an option that only contains a short-name.
092     * <p>
093     * It may be specified as requiring an argument.
094     * </p>
095     *
096     * @param opt Short single-character name of the option.
097     * @param hasArg flag signaling if an argument is required after this option.
098     * @param description Self-documenting description.
099     * @return the resulting Options instance.
100     */
101    public Options addOption(final String opt, final boolean hasArg, final String description) {
102        addOption(opt, null, hasArg, description);
103        return this;
104    }
105
106    /**
107     * Adds an option that only contains a short name.
108     * <p>
109     * The option does not take an argument.
110     * </p>
111     *
112     * @param opt Short single-character name of the option.
113     * @param description Self-documenting description.
114     * @return the resulting Options instance.
115     * @since 1.3
116     */
117    public Options addOption(final String opt, final String description) {
118        addOption(opt, null, false, description);
119        return this;
120    }
121
122    /**
123     * Adds an option that contains a short-name and a long-name.
124     * <p>
125     * It may be specified as requiring an argument.
126     * </p>
127     *
128     * @param opt Short single-character name of the option.
129     * @param longOpt Long multi-character name of the option.
130     * @param hasArg flag signaling if an argument is required after this option.
131     * @param description Self-documenting description.
132     * @return the resulting Options instance.
133     */
134    public Options addOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
135        addOption(new Option(opt, longOpt, hasArg, description));
136        return this;
137    }
138
139    /**
140     * Adds the specified option group.
141     * <p>
142     * An Option cannot be required if it is in an {@link OptionGroup}, either the group is required or nothing is required. This means that {@link Option} in
143     * the given group are set to optional.
144     * </p>
145     *
146     * @param optionGroup the OptionGroup that is to be added.
147     * @return the resulting Options instance.
148     */
149    public Options addOptionGroup(final OptionGroup optionGroup) {
150        if (optionGroup.isRequired()) {
151            requiredOpts.add(optionGroup);
152        }
153        for (final Option option : optionGroup.getOptions()) {
154            // an Option cannot be required if it is in an
155            // OptionGroup, either the group is required or
156            // nothing is required
157            option.setRequired(false);
158            final String key = option.getKey();
159            requiredOpts.remove(key);
160            addOption(option);
161            optionGroups.put(key, optionGroup);
162        }
163        return this;
164    }
165
166    /**
167     * Adds options to this option.  If any Option in {@code options} already exists
168     * in this Options an IllegalArgumentException is thrown.
169     *
170     * @param options the options to add.
171     * @return The resulting Options instance.
172     * @since 1.7.0
173     */
174    public Options addOptions(final Options options) {
175        for (final Option opt : options.getOptions()) {
176            if (hasOption(opt.getKey())) {
177                throw new IllegalArgumentException("Duplicate key: " + opt.getKey());
178            }
179            addOption(opt);
180        }
181        options.getOptionGroups().forEach(this::addOptionGroup);
182        return this;
183    }
184
185    /**
186     * Adds an option that contains a short-name and a long-name.
187     * <p>
188     * The added option is set as required. It may be specified as requiring an argument. This method is a shortcut for:
189     * </p>
190     * <pre>
191     * <code>
192     * Options option = new Option(opt, longOpt, hasArg, description);
193     * option.setRequired(true);
194     * options.add(option);
195     * </code>
196     * </pre>
197     *
198     * @param opt Short single-character name of the option.
199     * @param longOpt Long multi-character name of the option.
200     * @param hasArg flag signaling if an argument is required after this option.
201     * @param description Self-documenting description.
202     * @return the resulting Options instance.
203     * @since 1.4
204     */
205    public Options addRequiredOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
206        final Option option = new Option(opt, longOpt, hasArg, description);
207        option.setRequired(true);
208        addOption(option);
209        return this;
210    }
211
212    /*
213     * Retrieve the {@link Option} matching the long name specified.
214     * The leading hyphens in the name are ignored (up to 2).
215     *
216     * @param opt long name of the {@link Option}
217     * @return the option represented by opt
218     */
219    Option getLongOption(String opt)
220    {
221        opt = Util.stripLeadingHyphens(opt);
222
223        return longOpts.get(opt);
224    }
225
226    /**
227     * Gets the options with a long name starting with the name specified.
228     *
229     * @param opt the partial name of the option.
230     * @return the options matching the partial name specified, or an empty list if none matches.
231     * @since 1.3
232     */
233    public List<String> getMatchingOptions(final String opt) {
234        final String clean = Util.stripLeadingHyphens(opt);
235        final List<String> matchingOpts = new ArrayList<>();
236        // for a perfect match return the single option only
237        if (longOpts.containsKey(clean)) {
238            return Collections.singletonList(clean);
239        }
240        for (final String longOpt : longOpts.keySet()) {
241            if (longOpt.startsWith(clean)) {
242                matchingOpts.add(longOpt);
243            }
244        }
245        return matchingOpts;
246    }
247
248    /**
249     * Gets the {@link Option} matching the long or short name specified.
250     * <p>
251     * The leading hyphens in the name are ignored (up to 2).
252     * </p>
253     *
254     * @param opt short or long name of the {@link Option}.
255     * @return the option represented by opt.
256     */
257    public Option getOption(final String opt) {
258        final String clean = Util.stripLeadingHyphens(opt);
259        final Option option = shortOpts.get(clean);
260        return option != null ? option : longOpts.get(clean);
261    }
262
263    /**
264     * Gets the OptionGroup the {@code opt} belongs to.
265     *
266     * @param option the option whose OptionGroup is being queried.
267     * @return the OptionGroup if {@code opt} is part of an OptionGroup, otherwise return null.
268     */
269    public OptionGroup getOptionGroup(final Option option) {
270        return optionGroups.get(option.getKey());
271    }
272
273    /**
274     * Gets the OptionGroups that are members of this Options instance.
275     *
276     * @return a Collection of OptionGroup instances.
277     */
278    Collection<OptionGroup> getOptionGroups() {
279
280        // The optionGroups map will have duplicates in the values() results. We
281        // use the HashSet to filter out duplicates and return a collection of
282        // OpitonGroup. The decision to return a Collection rather than a set
283        // was probably to keep symmetry with the getOptions() method.
284        return new HashSet<>(optionGroups.values());
285    }
286
287    /**
288     * Gets a read-only list of options in this set.
289     *
290     * @return read-only Collection of {@link Option} objects in this descriptor.
291     */
292    public Collection<Option> getOptions() {
293        return Collections.unmodifiableCollection(helpOptions());
294    }
295
296    /**
297     * Gets the required options.
298     *
299     * @return read-only List of required options.
300     */
301    public List<?> getRequiredOptions() {
302        return Collections.unmodifiableList(requiredOpts);
303    }
304
305    /**
306     * Tests whether the named {@link Option} is a member of this {@link Options}.
307     *
308     * @param opt long name of the {@link Option}.
309     * @return true if the named {@link Option} is a member of this {@link Options}.
310     * @since 1.3
311     */
312    public boolean hasLongOption(final String opt) {
313        return longOpts.containsKey(Util.stripLeadingHyphens(opt));
314    }
315
316    /**
317     * Tests whether the named {@link Option} is a member of this {@link Options}.
318     *
319     * @param opt short or long name of the {@link Option}.
320     * @return true if the named {@link Option} is a member of this {@link Options}.
321     */
322    public boolean hasOption(final String opt) {
323        final String clean = Util.stripLeadingHyphens(opt);
324        return shortOpts.containsKey(clean) || longOpts.containsKey(clean);
325    }
326
327    /**
328     * Tests whether the named {@link Option} is a member of this {@link Options}.
329     *
330     * @param opt short name of the {@link Option}.
331     * @return true if the named {@link Option} is a member of this {@link Options}.
332     * @since 1.3
333     */
334    public boolean hasShortOption(final String opt) {
335        final String clean = Util.stripLeadingHyphens(opt);
336        return shortOpts.containsKey(clean);
337    }
338
339    /**
340     * Returns the Options for use by the HelpFormatter.
341     *
342     * @return the List of Options.
343     */
344    List<Option> helpOptions() {
345        return new ArrayList<>(shortOpts.values());
346    }
347
348    /**
349     * Dump state, suitable for debugging.
350     *
351     * @return Stringified form of this object.
352     */
353    @Override
354    public String toString() {
355        final StringBuilder buf = new StringBuilder();
356        buf.append("[ Options: [ short ");
357        buf.append(shortOpts.toString());
358        buf.append(" ] [ long ");
359        buf.append(longOpts);
360        buf.append(" ]");
361        return buf.toString();
362    }
363}