/** * Converts the specified commands into a string list. * * @param comp input completions * @return string list */ private static StringList list(final Enum<?>[] comp) { final StringList list = new StringList(); if (comp != null) { for (final Enum<?> c : comp) list.add(c.name().toLowerCase(Locale.ENGLISH)); } return list; }
/** * Returns the found command or throws an exception. * * @param cmp possible completions * @param par parent command * @param <E> token type * @return index * @throws QueryException query exception */ private <E extends Enum<E>> E consume(final Class<E> cmp, final Cmd par) throws QueryException { final String token = command(null); if (!suggest || token == null || !token.isEmpty()) { try { // return command reference; allow empty strings as input ("NULL") return Enum.valueOf(cmp, token == null ? "NULL" : token.toUpperCase(Locale.ENGLISH)); } catch (final IllegalArgumentException ignore) { } } final Enum<?>[] alt = startWith(cmp, token); // handle empty input if (token == null) { if (par != null) throw help(alt, par); if (suggest) throw error(alt, EXPECTING_CMD); return null; } // output error for similar commands final byte[] name = uc(token(token)); final Levenshtein ls = new Levenshtein(); for (final Enum<?> s : startWith(cmp, null)) { final byte[] sm = uc(token(s.name())); if (ls.similar(name, sm) && Cmd.class.isInstance(s)) { throw error(alt, UNKNOWN_SIMILAR_X, name, sm); } } // show unknown command error or available command extensions throw par == null ? error(alt, UNKNOWN_TRY_X, token) : help(alt, par); }
/** * Returns all commands that start with the specified user input. * * @param <T> token type * @param en available commands * @param prefix user input * @return completions */ private static <T extends Enum<T>> Enum<?>[] startWith(final Class<T> en, final String prefix) { Enum<?>[] list = new Enum<?>[0]; final String t = prefix == null ? "" : prefix.toUpperCase(Locale.ENGLISH); for (final Enum<?> e : en.getEnumConstants()) { if (e.name().startsWith(t)) { final int s = list.length; list = Array.copy(list, new Enum<?>[s + 1]); list[s] = e; } } return list; }