package mc.cliparser;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
public class CommandLineParser {
private final Set options = new HashSet<>();
public void addOption(Option option) {
options.add(option);
}
public CommandLine parse(String[] args) {
Set foundOptions = new HashSet<>();
AtomicReference refCurrentOption = new AtomicReference<>(null);
for (String arg : args) {
if (refCurrentOption.get() != null) {
refCurrentOption.get().value(arg);
foundOptions.add(refCurrentOption.get());
refCurrentOption.set(null);
} else {
parseOptArgs(arg, foundOptions, refCurrentOption);
}
}
return new CommandLine(foundOptions);
}
@SuppressWarnings("java:S125")
private void parseOptArgs(String arg, Set foundOptions, AtomicReference refCurrentOption) {
String optName;
if (arg.startsWith("--")) {
optName = arg.substring(2);
} else /*if (args[i].startsWith("-"))*/ {
optName = arg.substring(1);
}
for (Option option : options) {
if (optName.equals(option.shortName()) || optName.equals(option.longName())) {
if (option.hasArgs()) {
refCurrentOption.set(option);
} else {
foundOptions.add(option);
}
}
}
}
}