程式扎記: [ GroovyGN ] Parsing Commandline Arguments with CliBuilder

標籤

2014年4月22日 星期二

[ GroovyGN ] Parsing Commandline Arguments with CliBuilder

來源自 這裡 
Preface: 
Groovy is a great language to create scripts. Most of the time if we invoke the scripts we pass arguments to the script. These arguments are available as a String[] array in our script. For example to get the first argument we can use the following code s = args[0]. To have real argument handling in our script we use Groovy's CliBuilderclass. This class uses Jakarta Commons CLI under the hood. With CliBuilder we can define the argument options and parse the arguments. CliBuilder adds Groovyness by allowing us to invoke non-existing one-letter methods, which are turned into argument options with the one-letter shortcut. Furthermore we can use named parameters to define usage text, parser implementation, formatter implementation and option properties. 

Example: 
Let's see the CliBuilder in action. We create a script to show a date formatted according to defined arguments. If we don't define a date the current date is assumed. And furthermore we want to be able to define a prefix text, which is added before the formatted date (is empty by default). 
  1. import java.text.*  
  2.   
  3. def showdate(args) {  
  4.     def cli = new CliBuilder(usage: 'showdate.groovy -[chflms] [date] [prefix]')  
  5.     // Create the list of options.  
  6.     cli.with {  
  7.         h longOpt: 'help''Show usage information'  
  8.         c longOpt: 'format-custom', args: 1, argName: 'format''Format date with custom format defined by "format"'  
  9.         f longOpt: 'format-full',   'Use DateFormat#FULL format'  
  10.         l longOpt: 'format-long',   'Use DateFormat#LONG format'  
  11.         m longOpt: 'format-medium''Use DateFormat#MEDIUM format (default)'  
  12.         s longOpt: 'format-short',  'Use DateFormat#SHORT format'  
  13.     }  
  14.       
  15.     def options = cli.parse(args)  
  16.     if (!options) {  
  17.         return  
  18.     }  
  19.     // Show usage text when -h or --help option is used.  
  20.     if (options.h) {  
  21.         cli.usage()  
  22.         // Will output:  
  23.         // usage: showdate.groovy -[chflms] [date] [prefix]  
  24.         //  -c,--format-custom    Format date with custom format defined by "format"  
  25.         //  -f,--format-full              Use DateFormat#FULL format     
  26.         //  -h,--help                     Show usage information     
  27.         //  -l,--format-long              Use DateFormat#LONG format     
  28.         //  -m,--format-medium            Use DateFormat#MEDIUM format     
  29.         //  -s,--format-short             Use DateFormat#SHORT format     
  30.         return  
  31.     }  
  32.       
  33.     // Determine formatter.  
  34.     def df = DateFormat.getDateInstance(DateFormat.MEDIUM)  // Defeault.  
  35.     if (options.f) {  // Using short option.  
  36.         df = DateFormat.getDateInstance(DateFormat.FULL)   
  37.     } else if (options.'format-long') {  // Using long option.  
  38.         df = DateFormat.getDateInstance(DateFormat.LONG)   
  39.     } else if (options.'format-medium') {  
  40.         df = DateFormat.getDateInstance(DateFormat.MEDIUM)   
  41.     } else if (options.s) {  
  42.         df = DateFormat.getDateInstance(DateFormat.SHORT)   
  43.     } else if (options.'format-custom') {  
  44.         df = new SimpleDateFormat(options.c)  
  45.     }  
  46.   
  47.     // Handle all non-option arguments.  
  48.     def prefix = ''  // Default is empty prefix.  
  49.     def date = new Date()  // Default is current date.  
  50.     def extraArguments = options.arguments()  
  51.     if (extraArguments) {  
  52.         date = new Date().parse(extraArguments[0])  
  53.         // The rest of the arguments belong to the prefix.  
  54.         if (extraArguments.size() > 1) {  
  55.             prefix = extraArguments[1..-1].join(' ')  
  56.         }  
  57.     }  
  58.       
  59.     "$prefix${df.format(date)}"  
  60. }  
  61.   
  62. // Set locale for assertions.  
  63. Locale.setDefault(Locale.US)  
  64. assert '12/1/09' == showdate(['--format-short''2009/12/1'])  
  65. assert '12/1/09' == showdate(['-s''2009/12/1'])  
  66. assert 'Dec 1, 2009' == showdate(['2009/12/1'])  
  67. assert 'Dec 1, 2009' == showdate(['--format-medium''2009/12/1'])  
  68. assert 'Dec 1, 2009' == showdate(['-m''2009/12/1'])  
  69. assert 'December 1, 2009' == showdate(['--format-long''2009/12/1'])  
  70. assert 'December 1, 2009' == showdate(['-l''2009/12/1'])  
  71. assert 'Tuesday, December 1, 2009' == showdate(['--format-full''2009/12/1'])  
  72. assert 'Tuesday, December 1, 2009' == showdate(['-f''2009/12/1'])  
  73. assert 'Default date format:Dec 1, 2009' == showdate(['2009/12/1''Default''date''format:'])  
  74. assert 'Important date:Dec 1, 2009' == showdate(['-m''2009/12/1''Important date:'])  
  75. assert 'week 49 of the year 2009 AD' == showdate(['-c'"'week' w 'of the year' yyyy G"'2009/12/1'])  
  76. assert '2009/12/01' == showdate(['--format-custom''yyyy/MM/dd''2009/12/01'])  
  77. assert '2009' == showdate(['-cyyyy''2009/12/1'])  
  78. assert new Date().format('yyyy/MM/dd') == showdate(['--format-custom''yyyy/MM/dd'])  
  79.   
  80. println showdate(args)   
Supplement: 
Download Commons CLI

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!