-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathClis.java
73 lines (60 loc) · 2.34 KB
/
Clis.java
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
/*
* Copyright (c) 2022 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.commons.cli;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class Clis {
/**
* Parse an options object
*
* @param args - command line args
* @param options - expected options
* @return object with parsed values.
*/
public static CommandLine parse(final String[] args, final Options options, final CommandLineParser parser, final String commandLineSyntax) {
final HelpFormatter helpFormatter = new HelpFormatter();
try {
return parser.parse(options, args);
} catch (final ParseException e) {
if (commandLineSyntax != null && !commandLineSyntax.isEmpty()) {
helpFormatter.printHelp(commandLineSyntax, options);
}
throw new IllegalArgumentException(e);
}
}
public static CommandLine parse(final String[] args, final Options options, final String commandLineSyntax) {
return parse(args, options, new DefaultParser(), commandLineSyntax);
}
public static CommandLine parse(final String[] args, final Options options, final CommandLineParser parser) {
return parse(args, options, parser, null);
}
public static CommandLine parse(final String[] args, final Options options) {
return parse(args, options, new DefaultParser());
}
public static CommandLineParser getRelaxedParser() {
return new RelaxedParser();
}
// https://stackoverflow.com/questions/33874902/apache-commons-cli-1-3-1-how-to-ignore-unknown-arguments
private static class RelaxedParser extends DefaultParser {
@Override
public CommandLine parse(final Options options, final String[] arguments) throws ParseException {
final List<String> knownArgs = new ArrayList<>();
for (int i = 0; i < arguments.length; i++) {
if (options.hasOption(arguments[i])) {
knownArgs.add(arguments[i]);
if (i + 1 < arguments.length && options.getOption(arguments[i]).hasArg()) {
knownArgs.add(arguments[i + 1]);
}
}
}
return super.parse(options, knownArgs.toArray(new String[0]));
}
}
}