refactoring: Cli-Parser
This commit is contained in:
52
cli-parser/src/main/java/mc/cliparser/CommandLineParser.java
Normal file
52
cli-parser/src/main/java/mc/cliparser/CommandLineParser.java
Normal file
@@ -0,0 +1,52 @@
|
||||
package mc.cliparser;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public class CommandLineParser {
|
||||
|
||||
private final Set<Option> options = new HashSet<>();
|
||||
|
||||
public void addOption(Option option) {
|
||||
options.add(option);
|
||||
}
|
||||
|
||||
public CommandLine parse(String[] args) {
|
||||
|
||||
Set<Option> foundOptions = new HashSet<>();
|
||||
AtomicReference<Option> 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<Option> foundOptions, AtomicReference<Option> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user