Archived
0

refactoring: Cli-Parser

This commit is contained in:
2021-06-13 14:32:00 +03:00
parent 59b374e623
commit 95474a32c4
7 changed files with 172 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
package mc.cliparser;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import java.util.Set;
@RequiredArgsConstructor
@ToString
public class CommandLine {
private final Set<Option> options;
public boolean has(Option option) {
return options.contains(option);
}
}

View 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);
}
}
}
}
}

View File

@@ -0,0 +1,25 @@
package mc.cliparser;
import lombok.*;
import lombok.experimental.Accessors;
@Accessors(fluent = true)
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode
@ToString
public class Option {
@Getter
private final String shortName;
@Getter
private final String longName;
@Getter
private final boolean hasArgs;
@Getter
@Setter
private String value;
}