Added help message to display

This commit is contained in:
Isaac Parenteau
2018-09-13 19:38:24 -05:00
parent bbb3c08ba9
commit 696107ec8f
2 changed files with 102 additions and 21 deletions

View File

@ -21,7 +21,7 @@ public class ArgParser {
private List<Field> fields; private List<Field> fields;
private String programName; private String programName;
public ArgParser() { } private ArgParser() { }
public static ArgParser newBuilder() { public static ArgParser newBuilder() {
return new ArgParser(); return new ArgParser();
@ -29,6 +29,11 @@ public class ArgParser {
public ArgParser withArgClass(Class<?> argClass) { public ArgParser withArgClass(Class<?> argClass) {
this.argClass = argClass; this.argClass = argClass;
recollectFields();
return this;
}
private void recollectFields() {
this.fields = Stream.of(argClass.getDeclaredFields()) this.fields = Stream.of(argClass.getDeclaredFields())
.filter(f -> f.isAnnotationPresent(Parameter.class)) .filter(f -> f.isAnnotationPresent(Parameter.class))
.map(f -> { .map(f -> {
@ -55,17 +60,75 @@ public class ArgParser {
positional &= param.positional(); positional &= param.positional();
if (!positional && param.positional()) throw new IllegalArgumentException("All positional values have to be first in list"); if (!positional && param.positional()) throw new IllegalArgumentException("All positional values have to be first in list");
} }
return this;
} }
public ArgParser setProgramName(String name) { public ArgParser withProgramName(String name) {
this.programName = name; this.programName = name;
return this; return this;
} }
public String help() { public void help() {
return ""; recollectFields();
String name = programName == null || programName.isEmpty() ? "program" : programName;
StringBuilder sb = new StringBuilder();
sb.append(String.format("Usage: java -jar %s ", name));
for(Field f: fields) {
Parameter param = f.getAnnotation(Parameter.class);
if (param.positional()) {
sb.append(f.getName().toUpperCase());
sb.append(" ");
continue;
}
if(!param.required()) {
sb.append("[");
}
sb.append(String.format("%s %s", param.names()[0], f.getName().toUpperCase()));
if(!param.required()) {
sb.append("]");
}
sb.append(" ");
}
sb.append("\n");
int longestLength = 0;
for (Field f: fields) {
Parameter param = f.getAnnotation(Parameter.class);
if (param.positional()) {
if (f.getName().length() > longestLength) {
longestLength = f.getName().length();
}
continue;
}
String options = Stream.of(param.names()).collect(Collectors.joining(" | "));
if (options.length() > longestLength) {
longestLength = options.length();
}
}
for(Field f: fields) {
Parameter param = f.getAnnotation(Parameter.class);
if (param.positional()) {
sb.append(String.format("\t%-" + longestLength +"s : %s%n", f.getName().toUpperCase(), param.description()));
continue;
}
String options = Stream.of(param.names()).collect(Collectors.joining(" | "));
sb.append(String.format("\t%-" + longestLength +"s : %s %s%n", options, param.description(), param.required() ? "[required]": ""));
}
System.out.println(sb.toString());
} }
public <T> T parse(String[] args) { public <T> T parse(String[] args) {
@ -73,9 +136,14 @@ public class ArgParser {
return parseItem(args); return parseItem(args);
} catch (Exception ex) { } catch (Exception ex) {
System.err.println("An exception occured: " + ex.getMessage()); System.err.println("An exception occured: " + ex.getMessage());
System.err.println(help()); help();
ex.setStackTrace(new StackTraceElement[0]);
if (ex instanceof IllegalArgumentException) throw (IllegalArgumentException) ex;
IllegalArgumentException e = new IllegalArgumentException(ex.getMessage());
e.setStackTrace(new StackTraceElement[0]);
throw e;
} }
return null;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -142,6 +210,13 @@ public class ArgParser {
} }
} }
for(Field f : fields) {
Parameter param = f.getDeclaredAnnotation(Parameter.class);
if (param.required() && f.get(obj) == null) {
throw new IllegalArgumentException(String.format("Field %s is a required field. Value was empty", f.getName()));
}
}
return (T)obj; return (T)obj;
} }
@ -163,5 +238,4 @@ public class ArgParser {
} }
return l; return l;
} }
} }

View File

@ -11,33 +11,40 @@ import net.locusworks.argparser.annotations.Parameter;
import net.locusworks.argparser.converters.IntegerConverter; import net.locusworks.argparser.converters.IntegerConverter;
public class ArgParserTest { public class ArgParserTest {
public static class Args { public static class Args {
@Parameter(names="position2", positional=true, order=2) @Parameter(names="position2", positional=true, order=2)
public String position2; public String position2;
@Parameter(names="position1", positional=true, order=1) @Parameter(names="position1", positional=true, order=1)
public String position1; public String position1;
@Parameter(names="-list", variableArity=true) @Parameter(names= {"-l", "--list"}, description="List of values", variableArity=true)
public List<String> values; public List<String> values;
@Parameter(names="-count", converter=IntegerConverter.class) @Parameter(names="-count", converter=IntegerConverter.class, required=true)
public int count; public Integer count;
} }
@Test @Test
public void testArgParser() { public void testArgParser() {
String[] args = new String[] {"Hello", "World", "-list", "hell", "world", "-count", "1"}; String[] args = new String[] {"Hello", "World", "--list", "hell", "world", "-count", "1"};
Args arg = ArgParser.newBuilder().withArgClass(Args.class).parse(args); Args arg = ArgParser.newBuilder().withArgClass(Args.class).parse(args);
assertTrue(arg.position2.equals(args[0])); assertTrue(arg.position2.equals(args[0]));
assertTrue(arg.position1.equals(args[1])); assertTrue(arg.position1.equals(args[1]));
assertTrue(arg.values.size() == 2); assertTrue(arg.values.size() == 2);
assertTrue(arg.count == 1); assertTrue(arg.count == 1);
} }
@Test(expected=IllegalArgumentException.class)
public void testNoRequired() {
String[] args = new String[] {"Hello", "World", "--list", "hell", "world"};
ArgParser.newBuilder().withArgClass(Args.class).parse(args);
fail();
}
} }