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