OptionUtils.java

package net.morimekta.terminal.args.impl;

import java.util.regex.Pattern;

import static java.util.Objects.requireNonNull;

public final class OptionUtils {
    public static String requireValidArgumentName(String name) {
        requireNonNull(name, "name == null");
        if (name.isEmpty()) {
            throw new IllegalArgumentException("Empty argument name.");
        }
        if (!ARGUMENT_NAME_PATTERN.matcher(name).matches()) {
            throw new IllegalArgumentException("Invalid argument name \"" + name + "\", must be an identifier string, e.g.: \"name\".");
        }
        return name;
    }

    public static String requireValidLongName(String name) {
        requireNonNull(name, "name == null");
        if (name.isEmpty()) {
            throw new IllegalArgumentException("Empty long name.");
        }
        if (!LONG_NAME_PATTERN.matcher(name).matches()) {
            throw new IllegalArgumentException("Invalid name \"" + name + "\", must be an identifier string prefixed with '--', e.g.: \"--name\".");
        }
        return name;
    }

    public static String requireValidShortNames(String shortNames) {
        requireNonNull(shortNames, "shortNames == null");
        if (shortNames.isEmpty()) {
            throw new IllegalArgumentException("Empty short name character set.");
        }
        if (!SHORT_NAME_PATTERN.matcher(shortNames).matches()) {
            throw new IllegalArgumentException("Invalid short name set \"" + shortNames + "\", can only be letters, numbers, '?' or '!'.");
        }
        return shortNames;
    }

    public static String requireValidUsage(String usage) {
        requireNonNull(usage, "usage == null");
        if (usage.isEmpty()) {
            throw new IllegalArgumentException("Empty usage string.");
        }
        return usage;
    }

    private static final Pattern LONG_NAME_PATTERN     = Pattern.compile("--[a-zA-Z0-9]+(?:[-_][a-zA-Z0-9]+)*");
    private static final Pattern ARGUMENT_NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9]*(?:[-_][a-zA-Z0-9]+)*");
    private static final Pattern SHORT_NAME_PATTERN    = Pattern.compile("[a-zA-Z0-9?!]+");

    private OptionUtils() {}
}