forked from apache/commons-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoverview.html
More file actions
828 lines (799 loc) · 36 KB
/
Copy pathoverview.html
File metadata and controls
828 lines (799 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<title>Apache Commons CLI Overview</title>
</head>
<body>
<a href="https://commons.apache.org/cli"> <img src="org/apache/commons/cli/doc-files/logo.png" alt="Apache Commons CLI">
</a>
<section id="Introducing">
<h1>
<img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">1. Introducing Apache Commons CLI
</h1>
<p>The Apache Commons CLI component parses command-line arguments for your application.</p>
<p>Commons CLI parses command-line arguments using a descriptor of
valid options (long and short), potentially with arguments.</p>
<p>Command-line arguments may be of the typical {@code String[]}
form, but also may be a {@code java.util.List}. Indexes allow
for parsing only a portion of the command-line. Also, functionality
for parsing the command-line in phases is built in, allowing for
'cvs-style' command-lines, where some global options are specified
before a 'command' argument, and command-specific options are
specified after the command argument:
</p>
<pre><code>
myApp -p <port> command -p <printer>
</code></pre>
<p>
The homepage for the project is <a href="https://commons.apache.org">Apache Commons</a>
</p>
<p>
There are three stages to command line processing. They are the
definition, parsing and interrogation stages. The following
sections discuss each of these stages in turn, and show how
to implement them with CLI.
</p>
<section>
<h2>Defining the CLI</h2>
<p>
Each command line must define the set of options that will be used
to define the interface to the application.
</p>
<p>
CLI uses the <a href="javadocs/api-release/org/apache/commons/cli/Options.html">
Options</a> class, as a container for
<a href="javadocs/api-release/org/apache/commons/cli/Option.html">
Option</a> instances. There are two ways to create
<code>Option</code>s in CLI. One of them is via the constructors,
the other way is via the factory methods defined in
<code>Options</code>.
</p>
<p>
The <a href="#Using">Usage Scenarios</a> document provides
examples how to create an <code>Options</code> object and also
provides some real world examples.
</p>
<p>
The result of the definition stage is an <code>Options</code>
instance.
</p>
</section>
<section>
<h2>Parsing the CLI</h2>
<p>
The parsing stage is where the text passed into the
application via the command line is processed. The text is
processed according to the rules defined by the parser
implementation.
</p>
<p>
The <code>parse</code> method defined on
<a href="javadocs/api-release/org/apache/commons/cli/CommandLineParser.html">
CommandLineParser</a> takes an <code>Options</code>
instance and a <code>String[]</code> of arguments and
returns a
<a href="javadocs/api-release/org/apache/commons/cli/CommandLine.html">
CommandLine</a>.
</p>
<p>
The result of the parsing stage is a <code>CommandLine</code>
instance.
</p>
</section>
<section>
<h2>Interrogating the CLI</h2>
<p>
The interrogation stage is where the application queries the
<code>CommandLine</code> to decide what execution branch to
take depending on boolean options and uses the option values
to provide the application data.
</p>
<p>
This stage is implemented in the user code. The accessor methods
on <code>CommandLine</code> provide the interrogation capability
to the user code.
</p>
<p>
The result of the interrogation stage is that the user code
is fully informed of all the text that was supplied on the command
line and processed according to the parser and <code>Options</code>
rules.
</p>
</section>
</section>
<section id="Using">
<h1><img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">2. Using Apache Commons CLI</h1>
<p>
The following sections describe some example scenarios on how to
use CLI in applications.
</p>
<section>
<h2>Using a boolean option</h2>
<p>
A boolean option is represented on a command line by the presence
of the option, i.e. if the option is found then the option value
is <code>true</code>, otherwise the value is <code>false</code>.
</p>
<p>
The <code>DateApp</code> utility prints the current date to standard
output. If the <code>-t</code> option is present the current time is
also printed.
</p>
</section>
<section>
<h2>Creating the Options</h2>
<p>
An <a href="javadocs/api-release/org/apache/commons/cli/Options.html">
Options</a> object must be created and the <code>Option</code> must be
added to it.
</p>
<pre><code>
// create Options object
Options options = new Options();
// add t option
options.addOption("t", false, "display current time");
</code></pre>
<p>
The <code>addOption</code> method has three parameters. The first
parameter is a <code>java.lang.String</code> that represents the option.
The second parameter is a <code>boolean</code> that specifies whether the
option requires an argument or not. In the case of a boolean option
(sometimes referred to as a flag) an argument value is not present so
<code>false</code> is passed. The third parameter is the description
of the option. This description will be used in the usage text of the
application.
</p>
</section>
<section>
<h2>Parsing the command line arguments</h2>
<p>
The <code>parse</code> methods of <code>CommandLineParser</code> are used
to parse the command line arguments. There may be several implementations
of the <code>CommandLineParser</code> interface, the recommended one is the
<code>DefaultParser</code>.
</p>
<code>CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);</code>
<p>
Now we need to check if the <code>t</code> option is present. To do
this we will interrogate the
<a href="javadocs/api-release/org/apache/commons/cli/CommandLine.html">CommandLine
</a> object. The <code>hasOption</code> method takes a
<code>java.lang.String</code> parameter and returns <code>true</code> if the option
represented by the <code>java.lang.String</code> is present, otherwise
it returns <code>false</code>.
</p>
<pre><code>if(cmd.hasOption("t")) {
// print the date and time
} else {
// print the date
}</code></pre>
<p>
<em>Note</em>
</p>
<p>
As of version 1.5, the
<code>DefaultParser</code>'s constructor now has an override with
the signature <code>DefaultParser(final boolean allowPartialMatching)</code>.
Given the following code:
<code>final Options options = new Options();
options.addOption(new Option("d", "debug", false, "Turn on debug."));
options.addOption(new Option("e", "extract", false, "Turn on extract."));
options.addOption(new Option("o", "option", true, "Turn on option with argument."));</code>
we define "partial matching" as <code>-de</code> only matching the
<code>"debug"</code> option. We can consequently, now, turn this off and have
<code>-de</code> match both the <code>debug</code> option as well as the
<code>extract</code> option.
</p>
</section>
<section>
<h2>International Time</h2>
<p>
The <code>InternationalDateApp</code> utility extends the
<code>DateApp</code> utility by providing the ability to print the
date and time in any country in the world. To facilitate this a new
command line option, <code>c</code>, has been introduced.
</p>
<pre><code>// add c option
options.addOption("c", true, "country code");</code></pre>
<p>
The second parameter is <code>true</code> this time. This specifies that the
<code>c</code> option requires an argument value. If the required option
argument value is specified on the command line it is returned,
otherwise <code>null</code> is returned.
</p>
</section>
<section>
<h2>Retrieving the argument value</h2>
<p>
The <code>getOptionValue</code> methods of <code>CommandLine</code> are
used to retrieve the argument values of options.
</p>
<pre><code>// get c option value
String countryCode = cmd.getOptionValue("c");
if(countryCode == null) {
// print default date
} else {
// print date for country specified by countryCode
}</code></pre>
</section>
</section>
<section>
<h1><img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">3. Using Ant as an Example</h1>
<p>
<a href="https://ant.apache.org/">Ant</a> will be used
here to illustrate how to create the <code>Options</code> required. The following
is the help output for Ant.
</p>
<pre><code>ant [options] [target [target2 [target3] ...]]
Options:
-help print this message
-projecthelp print project help information
-version print the version information and exit
-quiet be extra quiet
-verbose be extra verbose
-debug print debugging information
-emacs produce logging information without adornments
-logfile <file> use given file for log
-logger <classname> the class which is to perform logging
-listener <classname> add an instance of class as a project listener
-buildfile <file> use given buildfile
-D<property>=<value> use value for given property
-find <file> search for buildfile towards the root of the
filesystem and use it</code></pre>
<section>
<h2>Defining Boolean Options</h2>
<p>
Lets create the boolean options for the application as they
are the easiest to create. For clarity the constructors for
<code>Option</code> are used here.
</p>
<pre><code>Option help = new Option("help", "print this message");
Option projecthelp = new Option("projecthelp", "print project help information");
Option version = new Option("version", "print the version information and exit");
Option quiet = new Option("quiet", "be extra quiet");
Option verbose = new Option("verbose", "be extra verbose");
Option debug = new Option("debug", "print debugging information");
Option emacs = new Option("emacs",
"produce logging information without adornments");</code></pre>
</section>
<section>
<h2>Defining Argument Options</h2>
<p>
The argument options are created using the <code>Option#Builder</code>.
</p>
<pre><code>Option logFile = Option.builder("logfile")
.argName("file")
.hasArg()
.desc("use given file for log")
.build();
Option logger = Option.builder("logger")
.argName("classname")
.hasArg()
.desc("the class which it to perform logging")
.build();
Option listener = Option.builder("listener")
.argName("classname")
.hasArg()
.desc("add an instance of class as "
+ "a project listener")
.build();
Option buildFile = Option.builder("buildfile")
.argName("file")
.hasArg()
.desc("use given buildfile")
.build();
Option find = Option.builder("find")
.argName("file")
.hasArg()
.desc("search for buildfile towards the "
+ "root of the filesystem and use it")
.build();</code></pre>
</section>
<section>
<h2>Defining Java Property Option</h2>
<p>
The last option to create is the Java property, and it is also created
using the Option class' Builder.
</p>
<code>Option property = Option property = Option.builder("D")
.hasArgs()
.valueSeparator('=')
.build();</code>
<p>
The map of properties specified by this option can later be retrieved by
calling <code>getOptionProperties("D")</code> on the <code>CommandLine</code>.
</p>
</section>
<section>
<h2>Creating the Options</h2>
<p>
Now that we have created each
<a href="javadocs/api-release/org/apache/commons/cli/Option.html">Option</a> we need
to create the
<a href="javadocs/api-release/org/apache/commons/cli/Options.html">Options</a>
instance. This is achieved using the
<a href="javadocs/api-release/org/apache/commons/cli/CommandLine.html#addOption(org.apache.commons.cli.Option)">addOption</a>
method of <code>Options</code>.
</p>
<pre><code>Options options = new Options();
options.addOption(help);
options.addOption(projecthelp);
options.addOption(version);
options.addOption(quiet);
options.addOption(verbose);
options.addOption(debug);
options.addOption(emacs);
options.addOption(logfile);
options.addOption(logger);
options.addOption(listener);
options.addOption(buildfile);
options.addOption(find);
options.addOption(property);</code></pre>
<p>
All the preparation is now complete, and we are now ready to
parse the command line arguments.
</p>
</section>
<section>
<h2>Creating the Parser</h2>
<p>
We now need to create a <code>CommandLineParser</code>. This will parse the command
line arguments, using the rules specified by the <code>Options</code> and
return an instance of <a href="javadocs/api-release/org/apache/commons/cli/CommandLine.html">CommandLine</a>.
</p>
<pre><code>public static void main(String[] args) {
// create the parser
CommandLineParser parser = new DefaultParser();
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
} catch (ParseException exp) {
// oops, something went wrong
System.err.println("Parsing failed. Reason: " + exp.getMessage());
}
}</code></pre>
</section>
<section>
<h2>Querying the commandline</h2>
<p>
To see if an option has been passed the <code>hasOption</code>
method is used. The argument value can be retrieved using
the <code>getOptionValue</code> method.
</p>
<pre><code>// has the buildfile argument been passed?
if (line.hasOption("buildfile")) {
// initialize the member variable
this.buildfile = line.getOptionValue("buildfile");
}</code></pre>
</section>
<section>
<h2>Displaying Usage and Help</h2>
<p>
CLI also provides the means to automatically generate usage
and help information. This is achieved with the
<a href="javadocs/api-release/org/apache/commons/cli/HelpFormatter.html">HelpFormatter</a>
class.
</p>
<pre><code>// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ant", options);</code></pre>
<p>
When executed the following output is produced:
</p>
<pre><code>usage: ant
-D <property=value> use value for given property
-buildfile <file> use given buildfile
-debug print debugging information
-emacs produce logging information without adornments
-file <file> search for buildfile towards the root of the
filesystem and use it
-help print this message
-listener <classname> add an instance of class as a project listener
-logger <classname> the class which it to perform logging
-projecthelp print project help information
-quiet be extra quiet
-verbose be extra verbose
-version print the version information and exit</code></pre>
<p>
If you also require to have a usage statement printed
then calling <code>formatter.printHelp("ant", options, true)</code>
will generate a usage statement as well as the help information.
</p>
</section>
</section>
<section>
<h1><img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">4. Creating an ls Example</h1>
<p>
One of the most widely used command line applications in the *nix world
is <code>ls</code>. Due to the large number of options required for <code>ls</code>
this example will only cover a small proportion of the options. The following
is a section of the help output.
</p>
<pre><code>Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuSUX nor --sort.
-a, --all do not hide entries starting with .
-A, --almost-all do not list implied . and ..
-b, --escape print octal escapes for non-graphic characters
--block-size=SIZE use SIZE-byte blocks
-B, --ignore-backups do not list implied entries ending with ~
-c with -lt: sort by, and show, ctime (time of last
modification of file status information)
with -l: show ctime and sort by name
otherwise: sort by ctime
-C list entries by columns</code></pre>
<p>
The following is the code that is used to create the
<a href="javadocs/api-release/org/apache/commons/cli/Options.html">Options</a> for this example.
</p>
<pre><code>// create the command line parser
CommandLineParser parser = new DefaultParser();
// create the Options
Options options = new Options();
options.addOption("a", "all", false, "do not hide entries starting with .");
options.addOption("A", "almost-all", false, "do not list implied . and ..");
options.addOption("b", "escape", false, "print octal escapes for non-graphic "
+ "characters");
options.addOption(Option.builder("SIZE").longOpt("block-size")
.desc("use SIZE-byte blocks")
.hasArg()
.build());
options.addOption("B", "ignore-backups", false, "do not list implied entries "
+ "ending with ~");
options.addOption("c", false, "with -lt: sort by, and show, ctime (time of last "
+ "modification of file status information) with "
+ "-l:show ctime and sort by name otherwise: sort "
+ "by ctime");
options.addOption("C", false, "list entries by columns");
String[] args = new String[]{ "--block-size=10" };
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
// validate that block-size has been set
if (line.hasOption("block-size")) {
// print the value of block-size
System.out.println(line.getOptionValue("block-size"));
}
} catch (ParseException exp) {
System.out.println("Unexpected exception:" + exp.getMessage());
} </code></pre>
</section>
<section>
<h1><img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">5. Converting (Parsing) Option Values</h1>
<p>
By in most cases the values on the command line are retrieved as Strings via the
<code>commandLine.getOptionValue(key)</code> command. However, it is possible for
the CLI library to convert the string into a different object. For example to specify
that the "count" option should return an Integer the following code could be used:
</p>
<pre><code>
public static void main(String[] args) {
Option count = Option.builder("count")
.hasArg()
.desc("the number of things")
.type(Integer.class)
.build();
Options options = new Options().addOption(count);
// create the parser
CommandLineParser parser = new DefaultParser();
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
} catch (ParseException exp) {
// oops, something went wrong
System.err.println("Parsing failed. Reason: " + exp.getMessage());
}
try {
Integer value = line.getParsedOptionValue(count);
System.out.format("The value is %s%n", value );
} catch (ParseException e) {
e.printStackTrace();
}
} </code></pre>
<p>
The value types natively supported by commons-cli are:
</p>
<ul>
<li>Object.class - The string value must be the name of a class with a no argument constructor</li>
<li>Class.class - The string value must be the name of a class</li>
<li>Date.class - The string value must be a date parsable by <code>new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")</code></li>
<li>File.class - The string value is the name of the file.</li>
<li>Path.class - The string value is the name of a Path.</li>
<li>Number.class - The string value is a number representation can can be converted into an Integer or a Double.</li>
<li>URL.class - The string value is the textual representation of a URL</li>
<li>FileInputStream.class - The string value is passed to <code>new FileInputStream(s)</code>.</li>
<li>Long.class - The string value is a valid argument to <code>Long.parseLong()</code>.</li>
<li>Integer.class - The string value is a valid argument to <code>Integer.parseInt()</code>.</li>
<li>Short.class - The string value is a valid argument to <code>Short.parseShort()</code>.</li>
<li>Byte.class - The string value is a valid argument to <code>Byte.parseByte()</code>.</li>
<li>Character.class - The string value is either a UTF-8 encoding for a character (e.g. "\\u0124") or the first character from the String."</li>
<li>Double.class - The string value is a valid argument to <code>Double.parseDouble()</code>.</li>
<li>Float.class - The string value is a valid argument to <code>Float.parseFloat()</code>.</li>
<li>BigInteger.class - The string value is a valid argument to <code>new BigInteger(s)</code>.</li>
<li>BigDecimal.class - The string value is a valid argument to <code>new BigDecimal(s)</code>.</li>
</ul>
<p>
Additional types may be added to the automatic parsing system by calling <code>TypeHandler.register(Class<T> clazz, Converter<T> converter)</code>.
The <code>Class<T></code> can be any defined class. The converter is a function that takes a <code>String</code> argument and returns an instance of
the class. Any exception thrown by the constructor will be caught and reported as a <code>ParseException</code>
</p>
<p>
Conversions can be specified without using the <code>TypeHandler</code> class by specifying the converter
directly during the option build. For example:
</p>
<pre><code>
Option fooOpt = Option.builder("foo")
.hasArg()
.desc("the foo arg")
.converter(Foo::new)
.build();</code></pre>
<p>
The above will create an option that passes the string value to the Foo constructor when <code>commandLine.getParsedOptionValue(fooOpt)</code> is called.
</p>
<p>
Conversions that are added to the TypeHandler or that are specified directly will not deserialize if the option is serialized unless the type is registered with the TypeHandler
before deserialization begins.
</p>
</section>
<section>
<h1><img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">6. Deprecating Options</h1>
<p>
Options may be marked as deprecated using ghe <code>Option.builder.deprecated()</code> method.
Additional information may be specified by passing a <code>DeprecatedAttributes</code> instance to the
<code>deprecated</code> method.
Usage of the deprecated option is announced when the presence of the option is checked
or the value of the option is retrieved. By default, the announcement printed to Standard out.
The HelpFormatter output will by default show the description prefixed by "[Deprecated]"
</p>
<p>
The examples below will implement <code>doSomething</code> in the following code block.
</p>
<pre><code>
public static void main(String[] args) {
Option n = Option.builder("n")
.deprecated(DeprecatedAttributes.builder()
.setDescription("Use '-count' instead")
.setForRemoval(true)
.setSince("now").get())
.hasArg()
.desc("the number of things")
.type(Integer.class)
.build();
Option count = Option.builder("count")
.hasArg()
.desc("the number of things")
.type(Integer.class)
.build();
Options options = new Options().addOption(n).addOption(count);
doSomething(options);
} </code></pre>
<section>
<h2>Changing Usage Announcement</h2>
<p>
The usage announcement may be changed by providing a <code>Consumer<Option></code> to the
<code>CommandLine.Builder.deprecatedHandler</code> method. This is commonly used to log usage
of deprecated options rather than printing them on the standard output.
</p>
<p>
for example if <code>doSomething</code> is implemented as:
</p>
<pre><code>
void doSomething(Options options) {
CommandLineParser parser = new DefaultParser();
CommandLine line;
try {
// parse the command line arguments
line = parser.parse(options, new String[] {"-n", "5"});
System.out.println("n=" + line.getParsedOptionValue("n"));
} catch (ParseException exp) {
// oops, something went wrong
System.err.println("Parsing failed. Reason: " + exp.getMessage());
}
} </code></pre>
<p>
The output of the run would be.
</p>
<pre><code>
Option 'n': Deprecated for removal since now: Use '-count' instead
n=5 </code></pre>
<p>
for example if <code>doSomething</code> is implemented as:
</p>
<pre><code>
void doSomething(Options options) {
Consumer<Option> deprecatedUsageAnnouncement = o -> {
final StringBuilder buf = new StringBuilder()
.append("'")
.append(o.getOpt())
.append("'");
if (o.getLongOpt() != null) {
buf.append("'").append(o.getLongOpt()).append("'");
}
System.err.printf("ERROR: Option %s: %s%n", buf, o.getDeprecated());
};
DefaultParser parser = DefaultParser.builder().setDeprecatedHandler(deprecatedUsageAnnouncement).build();
CommandLine line;
try {
// parse the command line arguments
line = parser.parse(options, new String[] {"-n", "5"});
System.out.println("n=" + line.getParsedOptionValue("n"));
} catch (ParseException exp) {
// oops, something went wrong
System.err.println("Parsing failed. Reason: " + exp.getMessage());
}
} </code></pre>
<p>
The output of the run would be.
</p>
<code>
ERROR: Option 'n': Deprecated for removal since now: Use '-count' instead
n=5 </code>
<p>
However, the first line would be printed on system err instead of system out.
</p>
</section>
<section>
<h2>Changing help format</h2>
<p>By default the help formater prints "[Deprecated]" in front of the description for the option. This can
be changed to display any values desired.
</p>
<p>
If <code>doSomething</code> is implemented as:
</p>
<pre><code>
void doSomething(Options options) {
HelpFormatter formatter = HelpFormatter.builder().get();
formatter.printHelp("Command line syntax:", options);
} </code></pre>
<p>
To output is
</p>
<pre><code>
usage: Command line syntax:
-count <arg> the number of things
-n <arg> [Deprecated] the number of things</code></pre>
<p>
The display of deprecated options may be changed through the use of the
<code>HelpFormatter.Builder.setShowDeprecated()</code> method.
</p>
<ul>
<li>Calling <code>HelpFormatter.Builder.setShowDeprecated(false)</code> will disable the "[Deprecated]" tag.</li>
<li>Calling <code>HelpFormatter.Builder.setShowDeprecated</code> with a <code>Function<Option, String></code>
will use the output of the function as the description for the option.</li>
</ul>
<p>
As an example of the second case above, changing the implementation of <code>doSomething</code> to
</p>
<pre><code>
void doSomething(Options options) {
Function<Option, String> disp = option -> String.format("%s. %s", HelpFormatter.getDescription(option),
option.getDeprecated().toString());
HelpFormatter formatter = HelpFormatter.builder().setShowDeprecated(disp).get();
formatter.printHelp("Command line syntax:", options);
} </code></pre>
<p>
changes the output to
</p>
<pre><code>
usage: Command line syntax:
-count <arg> the number of things
-n <arg> the number of things. Deprecated for removal since now:
Use '-count' instead</code></pre>
</section>
</section>
<section id="Properties">
<h1><img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">7. Defining Option Properties</h1>
<p>
The following are the properties that each
<a href="javadocs/api-release/org/apache/commons/cli/Option.html">Option</a> has. All of these
can be set using the accessors or using the methods
defined in the
<a href="javadocs/api-release/org/apache/commons/cli/Option.Builder.html">Option.Builder</a>.
</p>
<table>
<caption>Option Properties</caption>
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td>arg</td>
<td>boolean</td>
<td>A flag to say whether the option takes an argument.</td>
</tr>
<tr>
<td>args</td>
<td>boolean</td>
<td>A flag to say whether the option takes more than one argument.</td>
</tr>
<tr>
<td>argName</td>
<td>java.lang.String</td>
<td>The name of the argument value for the usage statement.</td>
</tr>
<tr>
<td>converter</td>
<td>org.apache.commons.cli.Converter<T, E extends Throwable></td>
<td>A FunctionalInterface that converts a String to type T and may throw an exception E. When
CommandLine.getParsedValue() is called this FunctionalInterface will perform the conversion from the
command line argument to the parsed type. This is used when a desired type is not registered, or to
provide a custom type implementation. The 'type' property is not required to use the 'converter' property.</td>
</tr>
<tr>
<td>deprecated</td>
<td>org.apache.commons.cli.DeprecatedAttributes</td>
<td>Marks the option as deprecated and has the deprecation properties.</td>
</tr>
<tr>
<td>description</td>
<td>java.lang.String</td>
<td>A description of the function of the option.</td>
</tr>
<tr>
<td>longOpt</td>
<td>java.lang.String</td>
<td>An alias and more descriptive identification string. May be null or not specified if 'opt' is provided.</td>
</tr>
<tr>
<td>opt</td>
<td>java.lang.String</td>
<td>The identification string of the Option. May be null or not specified if 'longOpt' is provided.</td>
</tr>
<tr>
<td>optionalArg</td>
<td>boolean</td>
<td>A flag to say whether the option's argument is optional.</td>
</tr>
<tr>
<td>required</td>
<td>boolean</td>
<td>A flag to say whether the option <b>must</b> appear on the command line.</td>
</tr>
<tr>
<td>type</td>
<td>java.lang.Class<?></td>
<td>The class of the object returned from getParsedValue(). The class must be registered in TypeHandler instance.
See also 'converter' property.</td>
</tr>
<tr>
<td>value</td>
<td>java.lang.String</td>
<td>The value of the option.</td>
</tr>
<tr>
<td>values</td>
<td>java.lang.String[]</td>
<td>The values of the option.</td>
</tr>
<tr>
<td>valueSeparator</td>
<td>char</td>
<td>The character value used to split the argument string, that is used in conjunction with multipleArgs e.g.
if the separator is ',' and the argument string is 'a,b,c' then there are three argument values, 'a', 'b'
and 'c'.</td>
</tr>
</table>
</section>
<h1>
<img src="org/apache/commons/cli/doc-files/leaf.svg" style="height: 1em; padding-right: 0.25em" alt="leaf">8. Requirements
</h1>
<ul>
<li>Java 8 or above.</li>
<li>If using OSGi, R7 or above.</li>
</ul>
</body>