View Javadoc
1   package org.argeo.cli;
2   
3   import java.io.StringWriter;
4   import java.util.Arrays;
5   import java.util.List;
6   import java.util.function.Function;
7   
8   import org.apache.commons.cli.CommandLine;
9   import org.apache.commons.cli.DefaultParser;
10  import org.apache.commons.cli.Options;
11  import org.apache.commons.cli.ParseException;
12  
13  /** A command that can be described. */
14  public interface DescribedCommand<T> extends Function<List<String>, T> {
15  	default Options getOptions() {
16  		return new Options();
17  	}
18  
19  	String getDescription();
20  
21  	default String getUsage() {
22  		return null;
23  	}
24  
25  	default String getExamples() {
26  		return null;
27  	}
28  
29  	default CommandLine toCommandLine(List<String> args) {
30  		try {
31  			DefaultParser parser = new DefaultParser();
32  			return parser.parse(getOptions(), args.toArray(new String[args.size()]));
33  		} catch (ParseException e) {
34  			throw new CommandArgsException(e);
35  		}
36  	}
37  
38  	/** In order to implement quickly a main method. */
39  	public static void mainImpl(DescribedCommand<?> command, String[] args) {
40  		try {
41  			Object output = command.apply(Arrays.asList(args));
42  			System.out.println(output);
43  			System.exit(0);
44  		} catch (IllegalArgumentException e) {
45  			StringWriter out = new StringWriter();
46  			HelpCommand.printHelp(command, out);
47  			System.err.println(out.toString());
48  			System.exit(1);
49  		} catch (Exception e) {
50  			e.printStackTrace();
51  			System.exit(1);
52  		}
53  	}
54  
55  }