Skip to content

Instantly share code, notes, and snippets.

@rednoah
Last active June 20, 2019 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rednoah/9eae301e3ace6067807f1c58bb97b12c to your computer and use it in GitHub Desktop.
Save rednoah/9eae301e3ace6067807f1c58bb97b12c to your computer and use it in GitHub Desktop.
ExecParameterConsumer implements IParameterConsumer
import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import picocli.CommandLine;
import picocli.CommandLine.IParameterConsumer;
import picocli.CommandLine.Model.ArgSpec;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
public class Find {
@Option(names = "-exec", parameterConsumer = ExecParameterConsumer.class)
public Exec exec;
@Parameters
public List<File> arguments;
public static void main(String[] args) {
Find find = CommandLine.populateCommand(new Find(), "a.txt", "-exec", "echo", "-n", "{}", ";", "b.txt", "c.txt");
assertEquals("echo -n {} [;]", find.exec.toString());
assertEquals("[a.txt, b.txt, c.txt]", find.arguments.toString());
find = CommandLine.populateCommand(new Find(), "a.txt", "-exec", "echo", "-n", "{}", "+", "b.txt", "c.txt");
assertEquals("echo -n {} [+]", find.exec.toString());
assertEquals("[a.txt, b.txt, c.txt]", find.arguments.toString());
find = CommandLine.populateCommand(new Find(), "-exec", "echo", "-n", "{}");
assertEquals("echo -n {} [;]", find.exec.toString());
find = CommandLine.populateCommand(new Find(), "-exec", "echo", "-n", "{}", "+");
assertEquals("echo -n {} [+]", find.exec.toString());
}
public static class Exec {
public boolean single;
public String[] command;
public static final String MARK_SINGLE = ";";
public static final String MARK_MULTI = "+";
@Override
public String toString() {
return String.format("%s [%s]", String.join(" ", command), single ? MARK_SINGLE : MARK_MULTI);
}
}
public static class ExecParameterConsumer implements IParameterConsumer {
@Override
public void consumeParameters(Stack<String> args, ArgSpec argSpec, CommandSpec commandSpec) {
LinkedList<String> command = new LinkedList<String>();
Set<String> marker = Set.of(Exec.MARK_SINGLE, Exec.MARK_MULTI);
while (!args.isEmpty() && (command.isEmpty() || !marker.contains(command.peekLast()))) {
command.add(args.pop());
}
Exec exec = new Exec();
if (marker.contains(command.peekLast())) {
exec.single = Exec.MARK_SINGLE.equals(command.removeLast());
exec.command = command.toArray(new String[0]);
} else {
exec.single = true;
exec.command = command.toArray(new String[0]);
}
argSpec.setValue(exec);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment