-
Notifications
You must be signed in to change notification settings - Fork 423
/
index.adoc
13612 lines (10827 loc) · 503 KB
/
index.adoc
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
= picocli - a mighty tiny command line interface
//:author: Remko Popma
//:email: rpopma@apache.org
:revnumber: 4.7.7-SNAPSHOT
:revdate: 2024-05-07
:toc: left
:numbered:
:toclevels: 2
:toc-title: Features
:source-highlighter: rouge
:rouge-languages: kotlin, groovy, scala
//:source-highlighter: highlightjs
//:highlightjs-theme: darkula
:icons: font
:imagesdir: images
:sectanchors:
:linkattrs:
:docinfo: shared-head,private
ifdef::env-github[]
:caution-caption: :fire:
:important-caption: :heavy_exclamation_mark:
:note-caption: :information_source:
:tip-caption: :bulb:
:warning-caption: :warning:
endif::[]
[link=https://github.com/remkop/picocli]
image::https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png[Fork me on GitHub,float="right"]
++++
<iframe src="https://ghbtns.com/github-btn.html?user=remkop&repo=picocli&type=star&count=true" frameborder="0" scrolling="0" width="170px" height="20px" style="float:right"></iframe>
++++
[quote]
Every main method deserves picocli!
image:logo/horizontal.png[picocli the Mighty Tiny Command Line Interface,width=800]
The user manual for the latest release is at https://picocli.info.
For the busy and impatient: there is also a link:quick-guide.html[Quick Guide].
== Introduction
Picocli aims to be the easiest way to create rich command line applications that can run on and off the JVM.
Considering picocli?
Check https://github.com/remkop/picocli/wiki/Feedback-from-Users[what happy users say] about picocli.
=== Overview
Picocli is a one-file framework for creating Java command line applications with almost zero code.
It supports a variety of command line syntax styles including POSIX, GNU, MS-DOS and more. It generates highly customizable usage help messages that use <<ANSI Colors and Styles,ANSI colors and styles>> to contrast important elements and reduce the cognitive load on the user.
Picocli-based applications can have link:autocomplete.html[command line TAB completion] showing available options, option parameters and subcommands, for any level of nested subcommands.
Picocli-based applications can be ahead-of-time compiled to a image:https://www.graalvm.org/resources/img/logo-colored.svg[GraalVM]
<<GraalVM Native Image,native image>>, with extremely fast startup time and lower memory requirements, which can be distributed as a single executable file.
Picocli <<Generate Man Page Documentation,generates beautiful documentation>> for your application (HTML, PDF and Unix man pages).
.An example usage help message with ANSI colors and styles
image:checksum-usage-help.png[Screenshot of usage help with Ansi codes enabled]
Another distinguishing feature of picocli is how it aims to let users run picocli-based applications without requiring picocli as an external dependency:
all the source code lives in a single file, to encourage application authors to include it _in source form_.
Picocli makes it easy to follow https://clig.dev/#guidelines[Command Line Interface Guidelines].
How it works: annotate your class and picocli initializes it from the command line arguments, converting the input to strongly typed values in the fields of your class.
TIP: Picocli also provides a <<Programmatic API,programmatic API>>, separately from the annotations API.
=== Example application
The example below shows a short but fully functional picocli-based `checksum` command line application.
// NOTE: other documents reference the [[CheckSum-application]] link; do not change it
.Java
[[CheckSum-application]]
[source,java,role="primary"]
----
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.io.File;
import java.math.BigInteger;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.concurrent.Callable;
@Command(name = "checksum", mixinStandardHelpOptions = true, version = "checksum 4.0",
description = "Prints the checksum (SHA-256 by default) of a file to STDOUT.")
class CheckSum implements Callable<Integer> {
@Parameters(index = "0", description = "The file whose checksum to calculate.")
private File file;
@Option(names = {"-a", "--algorithm"}, description = "MD5, SHA-1, SHA-256, ...")
private String algorithm = "SHA-256";
@Override
public Integer call() throws Exception { // your business logic goes here...
byte[] fileContents = Files.readAllBytes(file.toPath());
byte[] digest = MessageDigest.getInstance(algorithm).digest(fileContents);
System.out.printf("%0" + (digest.length*2) + "x%n", new BigInteger(1, digest));
return 0;
}
// this example implements Callable, so parsing, error handling and handling user
// requests for usage help or version help can be done with one line of code.
public static void main(String... args) {
int exitCode = new CommandLine(new CheckSum()).execute(args);
System.exit(exitCode);
}
}
----
// Note: this example deliberately does not have the callouts and detailed explanation of the Quick Guide;
// in this document we want to keep the introduction section very light-weight and high-level.
// The goal of the introduction is to show how easy picocli is.
// (The rest of this document has plenty of details.)
.Groovy
[[CheckSum-App-Groovy]]
[source,groovy,role="secondary"]
----
@Grab('info.picocli:picocli-groovy:4.7.7-SNAPSHOT')
import picocli.CommandLine
import static picocli.CommandLine.*
import java.security.MessageDigest
import java.util.concurrent.Callable
@Command(name = 'checksum', mixinStandardHelpOptions = true, version = 'checksum 4.0',
description = 'Prints the checksum (SHA-256 by default) of a file to STDOUT.')
class Checksum implements Callable<Integer> {
@Parameters(index = '0', description = 'The file whose checksum to calculate.')
File file
@Option(names = ['-a', '--algorithm'], description = 'MD5, SHA-1, SHA-256, ...')
String algorithm = 'SHA-256'
Integer call() throws Exception {
println MessageDigest.getInstance(algorithm).digest(file.bytes).encodeHex().toString()
0
}
static void main(String[] args) {
System.exit(new CommandLine(new Checksum()).execute(args))
}
}
----
.Groovy script
[[CheckSum-App-Groovy-Script]]
[source,groovy,role="secondary"]
----
@Grab('info.picocli:picocli-groovy:4.7.7-SNAPSHOT')
import static picocli.CommandLine.*
import groovy.transform.Field
import java.security.MessageDigest
@Command(name = 'checksum', mixinStandardHelpOptions = true, version = 'checksum 4.0',
description = 'Prints the checksum (SHA-256 by default) of a file to STDOUT.')
@picocli.groovy.PicocliScript
@Parameters(index = '0', description = 'The file whose checksum to calculate.')
@Field File file
@Option(names = ['-a', '--algorithm'], description = 'MD5, SHA-1, SHA-256, ...')
@Field String algorithm = 'SHA-256'
println MessageDigest.getInstance(algorithm).digest(file.bytes).encodeHex().toString()
----
.Kotlin
[[CheckSum-App-Kotlin]]
[source,kotlin,role="secondary"]
----
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
import java.io.File
import java.math.BigInteger
import java.nio.file.Files
import java.security.MessageDigest
import java.util.concurrent.Callable
import kotlin.system.exitProcess
@Command(name = "checksum", mixinStandardHelpOptions = true, version = ["checksum 4.0"],
description = ["Prints the checksum (SHA-256 by default) of a file to STDOUT."])
class Checksum : Callable<Int> {
@Parameters(index = "0", description = ["The file whose checksum to calculate."])
lateinit var file: File
@Option(names = ["-a", "--algorithm"], description = ["MD5, SHA-1, SHA-256, ..."])
var algorithm = "SHA-256"
override fun call(): Int {
val fileContents = Files.readAllBytes(file.toPath())
val digest = MessageDigest.getInstance(algorithm).digest(fileContents)
println(("%0" + digest.size * 2 + "x").format(BigInteger(1, digest)))
return 0
}
}
fun main(args: Array<String>) : Unit = exitProcess(CommandLine(Checksum()).execute(*args))
----
.Scala
[[CheckSum-App-Scala]]
[source,scala,role="secondary"]
----
import picocli.CommandLine
import picocli.CommandLine.{Command, Option, Parameters}
import java.io.File
import java.math.BigInteger
import java.nio.file.Files
import java.security.MessageDigest
import java.util.concurrent.Callable
@Command(name = "checksum", mixinStandardHelpOptions = true, version = Array("checksum 4.0"),
description = Array("Prints the checksum (SHA-256 by default) of a file to STDOUT."))
class Checksum extends Callable[Int] {
@Parameters(index = "0", description = Array("The file whose checksum to calculate."))
private var file: File = null
@Option(names = Array("-a", "--algorithm"), description = Array("MD5, SHA-1, SHA-256, ..."))
private var algorithm = "SHA-256"
def call(): Int = {
val fileContents = Files.readAllBytes(file.toPath)
val digest = MessageDigest.getInstance(algorithm).digest(fileContents)
println(("%0" + digest.size * 2 + "x").format(new BigInteger(1, digest)))
0
}
}
object Checksum {
def main(args: Array[String]): Unit = {
System.exit(new CommandLine(new Checksum()).execute(args: _*))
}
}
----
[TIP]
====
You can https://www.jdoodle.com/embed/v0/2mQM?stdin=1&arg=1[run this example online^].
Try it without arguments, with an option like `--help` or `--version`, or with a file name like `/usr/bin/java` as command line argument.
====
Implement `Runnable` or `Callable` and your command can be <<Executing Commands,executed>> in one line of code.
The example `main` method calls `CommandLine.execute` to parse the command line, handle errors, handle requests for usage and version help, and invoke the business logic. Applications can call `System.exit` with the returned exit code to signal success or failure to their caller.
The <<Mixin Standard Help Options,mixinStandardHelpOptions>> attribute adds `--help` and `--version` options to your application.
[TIP]
====
The picocli Quick Guide shows other https://picocli.info/quick-guide.html#_example_applications[sample applications] and explains them in more detail.
====
[TIP]
====
The https://github.com/remkop/picocli/tree/main/picocli-examples[picocli-examples] module in the picocli git repository has many more examples.
====
== Getting Started
You can add picocli as an external dependency to your project, or you can include it as source.
=== Add as External Dependency
Below are examples of configuring Gradle or Maven to use picocli as an external dependency in your project:
.Gradle
[source,groovy,role="primary"]
----
dependencies {
implementation 'info.picocli:picocli:4.7.7-SNAPSHOT'
}
----
.Maven
[source,xml,role="secondary"]
----
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>4.7.7-SNAPSHOT</version>
</dependency>
----
=== Add as Source
To include as source, get the source code from the link:https://github.com/remkop/picocli/blob/main/src/main/java/picocli/CommandLine.java[GitHub file]. Copy and paste it into a file called `CommandLine.java`, add it to your project, and enjoy!
=== Annotation Processor
The `picocli-codegen` module includes an annotation processor that can build a model from the picocli annotations at compile time rather than at runtime.
Enabling this annotation processor in your project is optional, but strongly recommended. Use this if you’re interested in:
* **Compile time error checking**. The annotation processor shows errors for invalid annotations and attributes immediately when you compile, instead of during testing at runtime, resulting in shorter feedback cycles.
* **<<GraalVM Native Image,GraalVM native images>>**. The annotation processor generates and updates https://www.graalvm.org/latest/reference-manual/native-image/overview/BuildConfiguration/[GraalVM configuration] files under
`META-INF/native-image/picocli-generated/$project` during compilation, to be included in the application jar.
This includes configuration files for https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/Reflection/[reflection], https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/Resources/[resources] and https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/DynamicProxy/[dynamic proxies].
By embedding these configuration files, your jar is instantly Graal-enabled.
In most cases no further configuration is needed when generating a native image.
==== Processor option: `project`
The picocli annotation processor supports a number of https://github.com/remkop/picocli/tree/main/picocli-codegen#picocli-processor-options[options], most important of which is the `project` option to control the output subdirectory: the generated files are written to `META-INF/native-image/picocli-generated/${project}`. A good convention is to use the Maven `${project.groupId}/${project.artifactId}` as the value; a unique subdirectory ensures your jar can be shaded with other jars that may also contain generated configuration files.
To configure this option, pass the `-Aproject=<some value>` to the javac compiler. The examples below show how to do this for Maven and Gradle.
==== Enabling the Annotation Processor
===== IDE
https://immutables.github.io/apt.html[This page] shows the steps to configure Eclipse and IntelliJ IDEA to enable annotation processing.
===== Using Build Tools
.Gradle
[source,groovy,role="primary"]
----
dependencies {
implementation 'info.picocli:picocli:4.7.7-SNAPSHOT'
annotationProcessor 'info.picocli:picocli-codegen:4.7.7-SNAPSHOT'
}
compileJava {
options.compilerArgs += ["-Aproject=${project.group}/${project.name}"]
}
----
.Maven
[source,xml,role="secondary"]
----
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<!-- annotationProcessorPaths requires maven-compiler-plugin version 3.5 or higher -->
<version>${maven-compiler-plugin-version}</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>info.picocli</groupId>
<artifactId>picocli-codegen</artifactId>
<version>4.7.7-SNAPSHOT</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Aproject=${project.groupId}/${project.artifactId}</arg>
</compilerArgs>
</configuration>
</plugin>
----
See the https://github.com/remkop/picocli/tree/main/picocli-codegen[`picocli-codegen` README] for more details.
===== Kotlin Projects Using Gradle
Kotlin projects should add the `kotlin-kapt` plugin to enable the Kotlin Annotation processing tool (https://kotlinlang.org/docs/reference/kapt.html[kapt]),
then replace `annotationProcessor` with `kapt`:
```
apply plugin: 'kotlin-kapt' // required
dependencies {
// ...
kapt 'info.picocli:picocli-codegen:4.7.7-SNAPSHOT'
}
```
And replace `compileJava.options.compilerArgs` with `kapt.arguments`:
```
kapt {
arguments {
arg("project", "${project.group}/${project.name}")
}
}
```
See the https://github.com/remkop/picocli/tree/main/picocli-codegen[`picocli-codegen` README] for more details.
=== Running the Application
After we successfully compiled our <<CheckSum-application,example `CheckSum` application>>, let's quickly look at how to run it.
There are many ways to run picocli-based applications, depending on whether we included picocli as source, created a jar for our application or not, and whether we created a shaded jar (also known as uber-jar) containing all dependencies.
Before we run our `CheckSum` application, let's create an example file whose checksum we want to print. For example:
[source,bash]
----
echo "hello" > hello.txt
----
Now, assuming we created a jar named `checksum.jar` containing our compiled `CheckSum.class`, we can run the application with `java -cp <classpath> <MainClass> [OPTIONS]`. For example:
[source,bash]
----
java -cp "picocli-4.7.7-SNAPSHOT.jar:checksum.jar" CheckSum --algorithm SHA-1 hello.txt
----
You may want to package your application in such a way that end users can invoke it with a short command like this:
[source,bash]
----
checksum --algorithm SHA-1 hello.txt
----
See the <<Packaging Your Application>> section for ideas on how to accomplish this.
== Options and Parameters
Command line arguments can be separated into _options_ and _positional parameters_.
Options have a name, positional parameters are usually the values that follow the options, but they may be mixed.
image:OptionsAndParameters2.png[Example command with annotated @Option and @Parameters]
Picocli has separate annotations for options and positional parameters.
=== Options
An option must have one or more `names`.
Picocli lets you use any option name you want.
Option names are case-sensitive by default, but this is <<Case Sensitivity,customizable>>.
TIP: You may be interested in this http://catb.org/~esr/writings/taoup/html/ch10s05.html#id2948149[list of common option names]. Following these conventions may make your application more intuitive to use for experienced users.
The below example shows options with one or more names, options that take an option parameter, and a <<Help Options,help>> option.
.Java
[source,java,role="primary"]
----
class Tar {
@Option(names = "-c", description = "create a new archive")
boolean create;
@Option(names = { "-f", "--file" }, paramLabel = "ARCHIVE", description = "the archive file")
File archive;
@Parameters(paramLabel = "FILE", description = "one or more files to archive")
File[] files;
@Option(names = { "-h", "--help" }, usageHelp = true, description = "display a help message")
private boolean helpRequested = false;
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
class Tar : Runnable {
@Option(names = ["-c"], description = ["create a new archive"])
var create: Boolean = false;
@Option(names = ["-f", "--file"], paramLabel = "ARCHIVE", description = ["the archive file"])
lateinit var archive: File;
@Parameters(paramLabel = "FILE", description = ["one or more files to archive"])
lateinit var files: Array<File>;
@Option(names = ["-h", "--help"], usageHelp = true, description = ["display a help message"])
private var helpRequested: Boolean = false;
}
----
Picocli matches the option names to set the field values.
.Java
[source,java,role="primary"]
----
String[] args = { "-c", "--file", "result.tar", "file1.txt", "file2.txt" };
Tar tar = new Tar();
new CommandLine(tar).parseArgs(args);
assert !tar.helpRequested;
assert tar.create;
assert tar.archive.equals(new File("result.tar"));
assert Arrays.equals(tar.files, new File[] {new File("file1.txt"), new File("file2.txt")});
----
.Kotlin
[source,kotlin,role="secondary"]
----
val args1 = arrayOf("-c", "--file", "result.tar", "file1.txt", "file2.txt")
var tar = Tar()
CommandLine(tar).parseArgs(*args1);
assert(!tar.helpRequested)
assert(tar.create)
assert(tar.archive.equals(File("result.tar")))
assert(Arrays.equals(tar.files, arrayOf<File>(File("file1.txt"), File("file2.txt"))))
----
=== Interactive (Password) Options
Picocli 3.5 introduced password support: for options and positional parameters marked as `interactive`, the user is prompted to enter a value on the console.
When running on Java 6 or higher, picocli will use the https://docs.oracle.com/javase/8/docs/api/java/io/Console.html#readPassword-java.lang.String-java.lang.Object...-[`Console.readPassword`] API so that user input is not echoed to the console.
From picocli 4.6, applications can choose to echo user input to the console by setting `echo = true`, and set the `prompt` text to control what is shown on the console when asking the user for input.
CAUTION: Interactive _positional parameters_ have a limitation: they must be followed by a non-interactive positional parameter.
Commands where the _last_ positional parameter is `interactive` are currently not supported.
==== Example
The example below demonstrates how an interactive option can be used to specify a password.
From picocli 3.9.6, interactive options can use type `char[]` instead of String, to allow applications to null out the array after use so that sensitive information is no longer resident in memory.
Example usage:
.Java
[source,java,role="primary"]
----
class Login implements Callable<Integer> {
@Option(names = {"-u", "--user"}, description = "User name")
String user;
@Option(names = {"-p", "--password"}, description = "Passphrase", interactive = true)
char[] password;
public Integer call() throws Exception {
byte[] bytes = new byte[password.length];
for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) password[i]; }
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(bytes);
System.out.printf("Hi %s, your password is hashed to %s.%n", user, base64(md.digest()));
// null out the arrays when done
Arrays.fill(bytes, (byte) 0);
Arrays.fill(password, ' ');
return 0;
}
private String base64(byte[] arr) { /* ... */ }
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
class Login : Callable<Int> {
@Option(names = ["-u", "--user"], description = ["User name"])
var user: String? = null
@Option(names = ["-p", "--password"], description = ["Passphrase"], interactive = true)
lateinit var password: CharArray
override fun call(): Int {
val bytes = ByteArray(password.size)
for (i in bytes.indices) { bytes[i] = password[i].toByte() }
val md = MessageDigest.getInstance("SHA-256")
md.update(bytes)
println(("Hi %s, your password is hashed to %s.").format(user, base64(md.digest())))
// null out the arrays when done
Arrays.fill(bytes, 0.toByte())
Arrays.fill(password, ' ')
return 0
}
private fun base64(arr: ByteArray): String { /* ... */ }
}
----
When this command is invoked like this:
.Java
[source,java,role="primary"]
----
new CommandLine(new Login()).execute("-u", "user123", "-p");
----
.Kotlin
[source,kotlin,role="secondary"]
----
CommandLine(Login()).execute("-u", "user123", "-p")
----
Then the user will be prompted to enter a value:
[source]
----
Enter value for --password (Passphrase):
----
When running on Java 6 or higher, the user input is not echoed to the console.
After the user enters a password value and presses enter, the `call()` method is invoked, which prints something like the following:
[source]
----
Hi user123, your passphrase is hashed to 75K3eLr+dx6JJFuJ7LwIpEpOFmwGZZkRiB84PURz6U8=.
----
==== Optionally Interactive
Interactive options by default cause the application to wait for input on stdin. For commands that need to be run interactively as well as in batch mode, it is useful if the option can optionally consume an argument from the command line.
The default <<Arity,arity>> for interactive options is zero, meaning that the option takes no parameters. From picocli 3.9.6, interactive options can also take a value from the command line if configured with `arity = "0..1"`. (See <<Optional Values>>.)
For example, if an application has these options:
.Java
[source,java,role="primary"]
----
@Option(names = "--user")
String user;
@Option(names = "--password", arity = "0..1", interactive = true)
char[] password;
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Option(names = ["--user"])
lateinit var user: String
@Option(names = ["--password"], arity = "0..1", interactive = true)
lateinit var password: CharArray
----
With the following input, the `password` field will be initialized to `"123"` without prompting the user for input:
----
--password 123 --user Joe
----
However, if the password is not specified, the user will be prompted to enter a value. In the following example, the password option has no parameter, so the user will be prompted to type in a value on the console:
----
--password --user Joe
----
[TIP]
.Providing Passwords to Batch Scripts Securely
====
Note that specifying a password in plain text on the command line or in scripts is not secure. There are alternatives that are more secure.
One idea is to add a separate different option (that could be named `--password:file`) that takes a `File` or `Path` parameter, where the application reads the password from the specified file.
Another idea is to add a separate different option (that could be named `--password:env`) that takes an environment variable name parameter, where the application gets the password from the user’s environment variables.
A command that combines either of these with an interactive `--password` option (with the default `arity = "0"`) allows end users to provide a password without specifying it in plain text on the command line. Such a command can be executed both interactively and in batch mode.
The https://github.com/remkop/picocli/blob/main/picocli-examples[`picocli-examples`] module has an example, coded both in https://github.com/remkop/picocli/blob/main/picocli-examples/src/main/java/picocli/examples/interactive/PasswordDemo.java[Java] and https://github.com/remkop/picocli/tree/main/picocli-examples/src/main/kotlin/picocli/examples/kotlin/interactive/PasswordDemo.kt[Kotlin].
====
[CAUTION]
.Interactive options and shell applications with JLine 2
====
Interactive options do not work in conjunction with JLine 2's `ConsoleReader`. Either implement a <<Custom Parameter Processing,`IParameterConsumer`>> which uses JLine2's `ConsoleReader` directly or use https://github.com/remkop/picocli/tree/main/picocli-shell-jline3[`picocli-shell-jline3`].
====
==== Forcing Interactive Input
Be aware that picocli only prompts the user when the interactive option is specified without parameter:
----
$ myprogram # option not specified: no prompting
You provided value 'null'
$ myprogram --interactive-option=abc # option specified with parameter: no prompting
You provided value 'abc'
$ myprogram --interactive-option # option specified WITHOUT parameter: prompt for input
Enter value for --interactive-option (...): # <--- type xxx and hit Enter
You provided value 'xxx'
----
Applications that also need the user to be prompted when the option is not specified, need to do this in the business logic.
For example:
.Java
[source,java,role="primary"]
----
@Command
public class Main implements Runnable {
@Option(names = "--interactive", interactive = true)
String value;
public void run() {
if (value == null && System.console() != null) {
// alternatively, use Console::readPassword
value = System.console().readLine("Enter value for --interactive: ");
}
System.out.println("You provided value '" + value + "'");
}
public static void main(String[] args) {
new CommandLine(new Main()).execute(args);
}
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Command
class Main : Runnable {
@Option(names = ["--interactive"], description = ["unattended run"], interactive = true)
var value: String? = null
override fun run() {
if (value == null && System.console() != null) {
// alternatively, use console::readPassword
value = System.console().readLine("Enter value for --interactive: ")
}
println("You provided value '$value'")
}
}
fun main(args: Array<String>) : Unit = exitProcess(CommandLine(Main()).execute(*args))
----
=== Short (POSIX) Options
Picocli supports https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02[POSIX clustered short options]:
one or more single-character options without option-arguments, followed by at most one option with an option-argument, can be grouped behind one '-' delimiter.
For example, given this annotated class:
.Java
[source,java,role="primary"]
----
class ClusteredShortOptions {
@Option(names = "-a") boolean aaa;
@Option(names = "-b") boolean bbb;
@Option(names = "-c") boolean ccc;
@Option(names = "-f") String file;
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
class ClusteredShortOptions {
@Option(names = ["-a"]) var aaa = false
@Option(names = ["-b"]) var bbb = false
@Option(names = ["-c"]) var ccc = false
@Option(names = ["-f"]) lateinit var file: String
}
----
The following command line arguments are all equivalent and parsing them will give the same result:
[source,bash]
----
<command> -abcfInputFile.txt
<command> -abcf=InputFile.txt
<command> -abc -f=InputFile.txt
<command> -ab -cf=InputFile.txt
<command> -a -b -c -fInputFile.txt
<command> -a -b -c -f InputFile.txt
<command> -a -b -c -f=InputFile.txt
...
----
[TIP]
.POSIX short options and usability
====
Applications can give a subtle hint to end users that an option is common and encouraged by providing both a short and a long name for an option.
Conversely, the absence of a short option can signal that the option is unusual or perhaps should be used with care.
====
=== Boolean Options
Boolean options usually don't need a parameter: it is enough to specify the option name on the command line.
.Java
[source,java,role="primary"]
----
class BooleanOptions {
@Option(names = "-x") boolean x;
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
class BooleanOptions {
@Option(names = ["-x"]) var x = false
}
----
The value of `x` is `false` by default, and is set to `true` (the opposite of the default) if the `-x` option is specified on the command line.
If the `-x` option is specified multiple times on the command line, the value of `x` remains `true`. (Prior to picocli 4.0, the value of `x` would "toggle" (flip to its opposite) for every `-x` option on the command line. This can still be <<Toggle Boolean Flags,configured>> if required.)
This is enough in most cases, but picocli offers alternatives for applications that need to get the value from something other than the default value. When the option is specified on the command line, the annotated field (or <<option-parameters-methods,method>>) is assigned a value, as follows:
* If the parser is configured to <<Toggle Boolean Flags,toggle boolean options>>, the opposite of the _current value_ is assigned. (This was the default prior to picocli 4.0.)
* If a <<fallbackValue-annotation, fallback value>> is defined, the fallback value is assigned.
* If the option is defined with a non-zero <<Arity,arity>>, and an option parameter was specified on the command line, this option <<Boolean Options with Parameters,parameter value is assigned>>.
* Otherwise, the value assigned is the logical opposite of the _default value_.
=== Negatable Options
From picocli 4.0, boolean options can be `negatable`.
.Java
[source,java,role="primary"]
----
@Command(name = "negatable-options-demo")
class NegatableOptionsDemo {
@Option(names = "--verbose", negatable = true) boolean verbose;
@Option(names = "-XX:+PrintGCDetails", negatable = true) boolean printGCDetails;
@Option(names = "-XX:-UseG1GC", negatable = true) boolean useG1GC = true;
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Command(name = "negatable-options-demo")
class NegatableOptionsDemo {
@Option(names = ["--verbose"], negatable = true) var verbose = false
@Option(names = ["-XX:+PrintGCDetails"], negatable = true) var printGCDetails = false
@Option(names = ["-XX:-UseG1GC"], negatable = true) var useG1GC = true
}
----
When an option is negatable, picocli will recognize negative aliases of the option on the command line.
The usage help for the above example looks like this:
----
Usage: negatable-options-demo [--[no-]verbose] [-XX:(+|-)PrintGCDetails]
[-XX:(+|-)UseG1GC]
--[no-]verbose Show verbose output
-XX:(+|-)PrintGCDetails
Prints GC details
-XX:(+|-)UseG1GC Use G1 algorithm for GC
----
For *nix-style long options, aliases have the prefix `no-` to the given names, for example `--no-verbose`.
For Java JVM-style options like `-XX:+PrintGCDetails`, the `:+` is turned into `:-` and vice versa.
Short option names are not given a negative alias by default. (This is <<Customizing Negatable Options,customizable>>.)
If the negated form of the option is found, for example `--no-verbose`, the value is set to `false`. Otherwise, with a regular call, for example `--verbose`, the value is set to `true`.
[TIP]
.Negatable options that are `true` by default
====
When a negatable option is `true` by default, give it both a `defaultValue` and a `fallbackValue` of `"true"`. For example:
.Java
[source,java,role="primary"]
----
@Option(names = "--backup", negatable = true,
defaultValue = "true", fallbackValue = "true",
description = "Make a backup. True by default.")
boolean backup;
----
.Kotlin
[source,kotlin,role="secondary"]
----
@Option(names = ["--backup"], negatable = true,
defaultValue = "true", fallbackValue = "true",
description = ["Make a backup. True by default."])
var backup = true
----
The table below shows the value assigned to the annotated option field for a number of possible user input strings:
//.Negatable option values for various user input strings
//[grid=cols,cols="10,10",options="header"]
//|===
//| End user input | Option value
//| (no args) | `true`
//| `--backup` | `true`
//| `--backup=true` | `true`
//| `--backup=false` | `false`
//| `--no-backup` | `false`
//| `--no-backup=true` | `false`
//| `--no-backup=false` | `true`
//|===
//
----
End user input Option value
-------------- ------------
(no args) true
--backup true
--backup=true true
--backup=false false
--no-backup false
--no-backup=true false
--no-backup=false true
----
====
=== Positional Parameters
Any command line arguments that are not subcommands or options (or option parameters) are interpreted as positional parameters.
Positional parameters generally follow the options but from picocli 2.0, positional parameters can be mixed with options on the command line.
==== Explicit Index
Use the (zero-based) `index` attribute to specify exactly which parameters to capture.
Array or collection fields can capture multiple values.
The `index` attribute accepts _range_ values, so an annotation like `@Parameters(index="2..4")` captures the arguments at index 2, 3 and 4. Range values can be _open-ended_. For example, `@Parameters(index="3..*")` captures all arguments from index 3 and up.
For example:
.Java
[source,java,role="primary"]
----
class PositionalParameters {
@Parameters(index = "0") InetAddress host;
@Parameters(index = "1") int port;
@Parameters(index = "2..*") File[] files;
@Parameters(hidden = true) // "hidden": don't show this parameter in usage help message
List<String> allParameters; // no "index" attribute: captures _all_ arguments
}
----
.Kotlin
[source,kotlin,role="secondary"]
----
class PositionalParameters {
@Parameters(index = "0") lateinit var host: InetAddress
@Parameters(index = "1") var port = 0
@Parameters(index = "2..*") lateinit var files: Array<File>
@Parameters(hidden = true) // "hidden": don't show this parameter in usage help message
lateinit var allParameters: List<String> // no "index" attribute: captures _all_ arguments
}
----
Picocli initializes fields with the values at the specified index in the arguments array.
.Java
[source,java,role="primary"]
----
String[] args = { "localhost", "12345", "file1.txt", "file2.txt" };
PositionalParameters params = CommandLine.populateCommand(new PositionalParameters(), args);
assert params.host.getHostName().equals("localhost");
assert params.port == 12345;
assert Arrays.equals(params.files, new File[] {new File("file1.txt"), new File("file2.txt")});
assert params.allParameters.equals(Arrays.asList(args));
----
.Kotlin
[source,kotlin,role="secondary"]
----
val args = arrayOf("localhost", "12345", "file1.txt", "file2.txt")
val params: PositionalParameters = CommandLine.populateCommand(PositionalParameters(), *args)
assert(params.host.getHostName().equals("localhost"))
assert(params.port === 12345)
assert(Arrays.equals(params.files, arrayOf(File("file1.txt"), File("file2.txt"))))
assert(params.allParameters.equals(Arrays.asList(*args)))
----
See <<Strongly Typed Everything>> for which types are supported out of the box and how to add custom types.
==== Omitting the Index
It is possible to omit the `index` attribute. This means different things for single-value and for multi-value positional parameters.
For *multi-value* positional parameters (arrays or collections), omitting the `index` attribute means the field captures _all_ positional parameters (the equivalent of `index = "0..*"`).
For *single-value* positional parameters, picocli's behaviour has changed since version 4.3:
prior to picocli 4.3, the default index for single-value positional parameters was also `index = "0..*"`, even though only one value (usually the first argument) can be captured.
From version 4.3, picocli assigns an index automatically, based on the other positional parameters defined in the same command.
[CAUTION]
====
Automatic indexes depend on the ability of Java reflection and Java annotation processors to iterate over fields in declaration order in the source code.
Officially this is not guaranteed by the Java spec.
In practice this has worked in Oracle JVMs and OpenJDK from Java 6, but there is some risk this may not work in the future or on other JVM's.
In general, for single-value positional parameters, using <<Explicit Index,explicit indexes>> is the safer option.
(Multi-value positional parameters can safely omit the `index` attribute.)
====
IMPORTANT: Methods cannot be iterated over in predictable order.
For applications with <<option-parameters-methods,`@Parameters`-annotated methods>> or combinations of `@Parameters`-annotated methods and `@Parameters`-annotated fields, we recommend using <<Explicit Index,explicit indexes>> for single-value positional parameters.
See <<Automatic Parameter Indexes>> for details.
=== Mixing Options and Positional Parameters
From picocli 2.0, positional parameters can be specified anywhere on the command line, they no longer need to follow the options.
For example:
.Java
[source,java,role="primary"]
----
class Mixed {
@Parameters
List<String> positional;