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      http://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 * It may flexibly parse long and short options, with or without values. Additionally, it may parse only a portion of a
035 * commandline, allowing for flexible multi-stage parsing.
036 *
037 * @see org.apache.commons.cli.CommandLine
038 */
039public class Options implements Serializable {
040    /** The serial version UID. */
041    private static final long serialVersionUID = 1L;
042
043    /** a map of the options with the character key */
044    private final Map<String, Option> shortOpts = new LinkedHashMap<>();
045
046    /** a map of the options with the long key */
047    private final Map<String, Option> longOpts = new LinkedHashMap<>();
048
049    /** a map of the required options */
050    // N.B. This can contain either a String (addOption) or an OptionGroup (addOptionGroup)
051    // TODO this seems wrong
052    private final List<Object> requiredOpts = new ArrayList<>();
053
054    /** a map of the option groups */
055    private final Map<String, OptionGroup> optionGroups = new LinkedHashMap<>();
056
057    /**
058     * Adds an option instance
059     *
060     * @param opt the option that is to be added
061     * @return the resulting Options instance
062     */
063    public Options addOption(final Option opt) {
064        final String key = opt.getKey();
065
066        // add it to the long option list
067        if (opt.hasLongOpt()) {
068            longOpts.put(opt.getLongOpt(), opt);
069        }
070
071        // if the option is required add it to the required list
072        if (opt.isRequired()) {
073            if (requiredOpts.contains(key)) {
074                requiredOpts.remove(requiredOpts.indexOf(key));
075            }
076            requiredOpts.add(key);
077        }
078
079        shortOpts.put(key, opt);
080
081        return this;
082    }
083
084    /**
085     * Add an option that only contains a short-name.
086     *
087     * <p>
088     * It may be specified as requiring an argument.
089     * </p>
090     *
091     * @param opt Short single-character name of the option.
092     * @param hasArg flag signalling if an argument is required after this option
093     * @param description Self-documenting description
094     * @return the resulting Options instance
095     */
096    public Options addOption(final String opt, final boolean hasArg, final String description) {
097        addOption(opt, null, hasArg, description);
098        return this;
099    }
100
101    /**
102     * Add an option that only contains a short name.
103     *
104     * <p>
105     * The option does not take an argument.
106     * </p>
107     *
108     * @param opt Short single-character name of the option.
109     * @param description Self-documenting description
110     * @return the resulting Options instance
111     * @since 1.3
112     */
113    public Options addOption(final String opt, final String description) {
114        addOption(opt, null, false, description);
115        return this;
116    }
117
118    /**
119     * Add an option that contains a short-name and a long-name.
120     *
121     * <p>
122     * It may be specified as requiring an argument.
123     * </p>
124     *
125     * @param opt Short single-character name of the option.
126     * @param longOpt Long multi-character name of the option.
127     * @param hasArg flag signalling if an argument is required after this option
128     * @param description Self-documenting description
129     * @return the resulting Options instance
130     */
131    public Options addOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
132        addOption(new Option(opt, longOpt, hasArg, description));
133        return this;
134    }
135
136    /**
137     * Add the specified option group.
138     *
139     * @param group the OptionGroup that is to be added
140     * @return the resulting Options instance
141     */
142    public Options addOptionGroup(final OptionGroup group) {
143        if (group.isRequired()) {
144            requiredOpts.add(group);
145        }
146
147        for (final Option option : group.getOptions()) {
148            // an Option cannot be required if it is in an
149            // OptionGroup, either the group is required or
150            // nothing is required
151            option.setRequired(false);
152            addOption(option);
153
154            optionGroups.put(option.getKey(), group);
155        }
156
157        return this;
158    }
159
160    /**
161     * Add an option that contains a short-name and a long-name.
162     *
163     * <p>
164     * The added option is set as required. It may be specified as requiring an argument. This method is a shortcut for:
165     * </p>
166     *
167     * <pre>
168     * <code>
169     * Options option = new Option(opt, longOpt, hasArg, description);
170     * option.setRequired(true);
171     * options.add(option);
172     * </code>
173     * </pre>
174     *
175     * @param opt Short single-character name of the option.
176     * @param longOpt Long multi-character name of the option.
177     * @param hasArg flag signalling if an argument is required after this option
178     * @param description Self-documenting description
179     * @return the resulting Options instance
180     * @since 1.4
181     */
182    public Options addRequiredOption(final String opt, final String longOpt, final boolean hasArg, final String description) {
183        final Option option = new Option(opt, longOpt, hasArg, description);
184        option.setRequired(true);
185        addOption(option);
186        return this;
187    }
188
189    /*
190     * Retrieve the {@link Option} matching the long name specified.
191     * The leading hyphens in the name are ignored (up to 2).
192     *
193     * @param opt long name of the {@link Option}
194     * @return the option represented by opt
195     */
196    Option getLongOption(String opt)
197    {
198        opt = Util.stripLeadingHyphens(opt);
199
200        return longOpts.get(opt);
201    }
202
203    /**
204     * Gets the options with a long name starting with the name specified.
205     *
206     * @param opt the partial name of the option
207     * @return the options matching the partial name specified, or an empty list if none matches
208     * @since 1.3
209     */
210    public List<String> getMatchingOptions(String opt) {
211        opt = Util.stripLeadingHyphens(opt);
212
213        final List<String> matchingOpts = new ArrayList<>();
214
215        // for a perfect match return the single option only
216        if (longOpts.containsKey(opt)) {
217            return Collections.singletonList(opt);
218        }
219
220        for (final String longOpt : longOpts.keySet()) {
221            if (longOpt.startsWith(opt)) {
222                matchingOpts.add(longOpt);
223            }
224        }
225
226        return matchingOpts;
227    }
228
229    /**
230     * Gets the {@link Option} matching the long or short name specified.
231     *
232     * <p>
233     * The leading hyphens in the name are ignored (up to 2).
234     * </p>
235     *
236     * @param opt short or long name of the {@link Option}
237     * @return the option represented by opt
238     */
239    public Option getOption(String opt) {
240        opt = Util.stripLeadingHyphens(opt);
241
242        if (shortOpts.containsKey(opt)) {
243            return shortOpts.get(opt);
244        }
245
246        return longOpts.get(opt);
247    }
248
249    /**
250     * Gets the OptionGroup the {@code opt} belongs to.
251     *
252     * @param opt the option whose OptionGroup is being queried.
253     * @return the OptionGroup if {@code opt} is part of an OptionGroup, otherwise return null
254     */
255    public OptionGroup getOptionGroup(final Option opt) {
256        return optionGroups.get(opt.getKey());
257    }
258
259    /**
260     * Gets the OptionGroups that are members of this Options instance.
261     *
262     * @return a Collection of OptionGroup instances.
263     */
264    Collection<OptionGroup> getOptionGroups() {
265        return new HashSet<>(optionGroups.values());
266    }
267
268    /**
269     * Gets a read-only list of options in this set
270     *
271     * @return read-only Collection of {@link Option} objects in this descriptor
272     */
273    public Collection<Option> getOptions() {
274        return Collections.unmodifiableCollection(helpOptions());
275    }
276
277    /**
278     * Gets the required options.
279     *
280     * @return read-only List of required options
281     */
282    public List getRequiredOptions() {
283        return Collections.unmodifiableList(requiredOpts);
284    }
285
286    /**
287     * Returns whether the named {@link Option} is a member of this {@link Options}.
288     *
289     * @param opt long name of the {@link Option}
290     * @return true if the named {@link Option} is a member of this {@link Options}
291     * @since 1.3
292     */
293    public boolean hasLongOption(String opt) {
294        opt = Util.stripLeadingHyphens(opt);
295
296        return longOpts.containsKey(opt);
297    }
298
299    /**
300     * Returns whether the named {@link Option} is a member of this {@link Options}.
301     *
302     * @param opt short or long name of the {@link Option}
303     * @return true if the named {@link Option} is a member of this {@link Options}
304     */
305    public boolean hasOption(String opt) {
306        opt = Util.stripLeadingHyphens(opt);
307
308        return shortOpts.containsKey(opt) || longOpts.containsKey(opt);
309    }
310
311    /**
312     * Returns whether the named {@link Option} is a member of this {@link Options}.
313     *
314     * @param opt short name of the {@link Option}
315     * @return true if the named {@link Option} is a member of this {@link Options}
316     * @since 1.3
317     */
318    public boolean hasShortOption(String opt) {
319        opt = Util.stripLeadingHyphens(opt);
320
321        return shortOpts.containsKey(opt);
322    }
323
324    /**
325     * Returns the Options for use by the HelpFormatter.
326     *
327     * @return the List of Options
328     */
329    List<Option> helpOptions() {
330        return new ArrayList<>(shortOpts.values());
331    }
332
333    /**
334     * Dump state, suitable for debugging.
335     *
336     * @return Stringified form of this object
337     */
338    @Override
339    public String toString() {
340        final StringBuilder buf = new StringBuilder();
341
342        buf.append("[ Options: [ short ");
343        buf.append(shortOpts.toString());
344        buf.append(" ] [ long ");
345        buf.append(longOpts);
346        buf.append(" ]");
347
348        return buf.toString();
349    }
350}