1
1
/*
2
- * Copyright 2002-2020 the original author or authors.
2
+ * Copyright 2002-2023 the original author or authors.
3
3
*
4
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
5
* you may not use this file except in compliance with the License.
30
30
* <em>without spaces</em> by an equals sign ("="). The value may optionally be
31
31
* an empty string.
32
32
*
33
+ * <p>This parser supports the POSIX "end of options" delimiter, meaning that
34
+ * any {@code "--"} (empty option name) in the command signals that all remaining
35
+ * arguments will non-optional. For example, here {@code "--opt=ignored"} is considered
36
+ * as a non-optional argument.
37
+ * <pre class="code">
38
+ * --foo=bar -- --opt=ignored</pre>
39
+ *
33
40
* <h4>Valid examples of option arguments</h4>
34
41
* <pre class="code">
35
42
* --foo
53
60
*
54
61
* @author Chris Beams
55
62
* @author Sam Brannen
63
+ * @author Brian Clozel
56
64
* @since 3.1
57
65
*/
58
66
class SimpleCommandLineArgsParser {
@@ -65,23 +73,26 @@ class SimpleCommandLineArgsParser {
65
73
*/
66
74
public CommandLineArgs parse (String ... args ) {
67
75
CommandLineArgs commandLineArgs = new CommandLineArgs ();
76
+ boolean endOfOptions = false ;
68
77
for (String arg : args ) {
69
- if (arg .startsWith ("--" )) {
78
+ if (! endOfOptions && arg .startsWith ("--" )) {
70
79
String optionText = arg .substring (2 );
71
- String optionName ;
72
- String optionValue = null ;
73
80
int indexOfEqualsSign = optionText .indexOf ('=' );
74
81
if (indexOfEqualsSign > -1 ) {
75
- optionName = optionText .substring (0 , indexOfEqualsSign );
76
- optionValue = optionText .substring (indexOfEqualsSign + 1 );
82
+ String optionName = optionText .substring (0 , indexOfEqualsSign );
83
+ String optionValue = optionText .substring (indexOfEqualsSign + 1 );
84
+ if (optionName .isEmpty ()) {
85
+ throw new IllegalArgumentException ("Invalid argument syntax: " + arg );
86
+ }
87
+ commandLineArgs .addOptionArg (optionName , optionValue );
77
88
}
78
- else {
79
- optionName = optionText ;
89
+ else if (! optionText . isEmpty ()) {
90
+ commandLineArgs . addOptionArg ( optionText , null ) ;
80
91
}
81
- if (optionName .isEmpty ()) {
82
- throw new IllegalArgumentException ("Invalid argument syntax: " + arg );
92
+ else {
93
+ // '--' End of options delimiter, all remaining args must be non-optional
94
+ endOfOptions = true ;
83
95
}
84
- commandLineArgs .addOptionArg (optionName , optionValue );
85
96
}
86
97
else {
87
98
commandLineArgs .addNonOptionArg (arg );
0 commit comments