001package runwar.options; 002import java.io.File; 003import java.util.HashSet; 004import java.util.Map; 005 006import static java.io.File.*; 007import static java.util.Arrays.*; 008 009import joptsimple.HelpFormatter; 010import joptsimple.OptionDescriptor; 011import joptsimple.OptionParser; 012 013import static joptsimple.util.DateConverter.*; 014 015public class HelpFormatterExample { 016 static class MyFormatter implements HelpFormatter { 017 public String format( Map<String, ? extends OptionDescriptor> options ) { 018 StringBuilder buffer = new StringBuilder(); 019 for ( OptionDescriptor each : new HashSet<>( options.values() ) ) { 020 buffer.append( lineFor( each ) ); 021 } 022 return buffer.toString(); 023 } 024 025 private String lineFor( OptionDescriptor descriptor ) { 026 if ( descriptor.representsNonOptions() ) { 027 return descriptor.argumentDescription() + '(' + descriptor.argumentTypeIndicator() + "): " 028 + descriptor.description() + System.getProperty( "line.separator" ); 029 } 030 031 StringBuilder line = new StringBuilder( descriptor.options().toString() ); 032 line.append( ": description = " ).append( descriptor.description() ); 033 line.append( ", required = " ).append( descriptor.isRequired() ); 034 line.append( ", accepts arguments = " ).append( descriptor.acceptsArguments() ); 035 line.append( ", requires argument = " ).append( descriptor.requiresArgument() ); 036 line.append( ", argument description = " ).append( descriptor.argumentDescription() ); 037 line.append( ", argument type indicator = " ).append( descriptor.argumentTypeIndicator() ); 038 line.append( ", default values = " ).append( descriptor.defaultValues() ); 039 line.append( System.getProperty( "line.separator" ) ); 040 return line.toString(); 041 } 042 } 043 044 public static void main( String[] args ) throws Exception { 045 OptionParser parser = new OptionParser() { 046 { 047 accepts( "c" ).withRequiredArg().ofType( Integer.class ) 048 .describedAs( "count" ).defaultsTo( 1 ); 049 accepts( "q" ).withOptionalArg().ofType( Double.class ) 050 .describedAs( "quantity" ); 051 accepts( "d", "some date" ).withRequiredArg().required() 052 .withValuesConvertedBy( datePattern( "MM/dd/yy" ) ); 053 acceptsAll( asList( "v", "talkative", "chatty" ), "be more verbose" ); 054 accepts( "output-file" ).withOptionalArg().ofType( File.class ) 055 .describedAs( "file" ); 056 acceptsAll( asList( "h", "?" ), "show help" ).forHelp(); 057 acceptsAll( asList( "cp", "classpath" ) ).withRequiredArg() 058 .describedAs( "path1" + pathSeparatorChar + "path2:..." ) 059 .ofType( File.class ) 060 .withValuesSeparatedBy( pathSeparatorChar ); 061 nonOptions( "files to chew on" ).ofType( File.class ).describedAs( "input files" ); 062 } 063 }; 064 065 parser.formatHelpWith( new MyFormatter() ); 066 parser.printHelpOn( System.out ); 067 } 068}