1 | |
package com.lexicalscope.jewel.cli.parser; |
2 | |
|
3 | |
import com.lexicalscope.jewel.cli.ArgumentValidationException; |
4 | |
|
5 | 244 | class ArgumentParserImpl implements ArgumentParser |
6 | |
{ |
7 | |
|
8 | |
|
9 | |
|
10 | |
@Override |
11 | |
public void parseArguments(final ParsedArguments parsedArguments, final String... arguments) throws ArgumentValidationException |
12 | |
{ |
13 | 244 | boolean finishedOptions = false; |
14 | 818 | for (final String argument : arguments) |
15 | |
{ |
16 | 578 | if(finishedOptions) |
17 | |
{ |
18 | 16 | parsedArguments.addValue(argument); |
19 | |
} |
20 | |
else |
21 | |
{ |
22 | 562 | finishedOptions = add(parsedArguments, argument); |
23 | |
} |
24 | |
} |
25 | 240 | } |
26 | |
|
27 | |
private boolean add(final ParsedArguments parsedArguments, final String argument) throws ArgumentValidationException |
28 | |
{ |
29 | 562 | if (startsWithDash(argument)) |
30 | |
{ |
31 | 260 | if (startsWithDoubleDash(argument)) |
32 | |
{ |
33 | 240 | if (argument.length() > 2) |
34 | |
{ |
35 | 230 | addOptionAndValue(parsedArguments, argument); |
36 | |
} |
37 | |
else |
38 | |
{ |
39 | 10 | parsedArguments.unparsedOptionsFollow(); |
40 | 10 | return true; |
41 | |
} |
42 | |
} |
43 | |
else |
44 | |
{ |
45 | 20 | addConjoinedOptions(parsedArguments, argument.substring(1)); |
46 | |
} |
47 | |
} |
48 | |
else |
49 | |
{ |
50 | 302 | parsedArguments.addValue(argument); |
51 | |
} |
52 | 548 | return false; |
53 | |
} |
54 | |
|
55 | |
private void addConjoinedOptions(final ParsedArguments parsedArguments, final String options) throws ArgumentValidationException |
56 | |
{ |
57 | 56 | for (int i = 0; i < options.length(); i++) |
58 | |
{ |
59 | 36 | parsedArguments.addOption(options.substring(i, i + 1)); |
60 | |
} |
61 | 20 | } |
62 | |
|
63 | |
private void addOptionAndValue(final ParsedArguments parsedArguments, final String argument) throws ArgumentValidationException |
64 | |
{ |
65 | 230 | if (argument.contains("=")) |
66 | |
{ |
67 | 2 | final int separatorIndex = argument.indexOf("="); |
68 | 2 | parsedArguments.addOption(argument.substring(2, separatorIndex).trim()); |
69 | |
|
70 | 2 | if (argument.length() > separatorIndex + 1) |
71 | |
{ |
72 | 2 | parsedArguments.addValue(argument.substring(separatorIndex + 1).trim()); |
73 | |
} |
74 | 2 | } |
75 | |
else |
76 | |
{ |
77 | 228 | parsedArguments.addOption(argument.substring(2, argument.length()).trim()); |
78 | |
} |
79 | 226 | } |
80 | |
|
81 | |
private boolean startsWithDash(final String argument) |
82 | |
{ |
83 | 562 | return argument.length() > 1 && argument.startsWith("-"); |
84 | |
} |
85 | |
|
86 | |
private boolean startsWithDoubleDash(final String argument) |
87 | |
{ |
88 | 260 | return argument.startsWith("--"); |
89 | |
} |
90 | |
} |