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.util.Collection;
021import java.util.Iterator;
022
023/**
024 * Exception thrown when an option can't be identified from a partial name.
025 *
026 * @since 1.3
027 */
028public class AmbiguousOptionException extends UnrecognizedOptionException {
029    /**
030     * This exception {@code serialVersionUID}.
031     */
032    private static final long serialVersionUID = 5829816121277947229L;
033
034    /**
035     * Build the exception message from the specified list of options.
036     *
037     * @param option
038     * @param matchingOptions
039     * @return
040     */
041    private static String createMessage(final String option, final Collection<String> matchingOptions) {
042        final StringBuilder buf = new StringBuilder("Ambiguous option: '");
043        buf.append(option);
044        buf.append("'  (could be: ");
045
046        final Iterator<String> it = matchingOptions.iterator();
047        while (it.hasNext()) {
048            buf.append(Char.APOS);
049            buf.append(it.next());
050            buf.append(Char.APOS);
051            if (it.hasNext()) {
052                buf.append(", ");
053            }
054        }
055        buf.append(")");
056
057        return buf.toString();
058    }
059
060    /** The list of options matching the partial name specified */
061    private final Collection<String> matchingOptions;
062
063    /**
064     * Constructs a new AmbiguousOptionException.
065     *
066     * @param option the partial option name
067     * @param matchingOptions the options matching the name
068     */
069    public AmbiguousOptionException(final String option, final Collection<String> matchingOptions) {
070        super(createMessage(option, matchingOptions), option);
071        this.matchingOptions = matchingOptions;
072    }
073
074    /**
075     * Gets the options matching the partial name.
076     *
077     * @return a collection of options matching the name
078     */
079    public Collection<String> getMatchingOptions() {
080        return matchingOptions;
081    }
082}