1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.cling.invoker.mvn;
20
21 import java.io.IOException;
22 import java.nio.charset.Charset;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.stream.Stream;
28
29 import org.apache.commons.cli.ParseException;
30 import org.apache.maven.api.cli.Options;
31 import org.apache.maven.api.cli.ParserException;
32 import org.apache.maven.api.cli.mvn.MavenOptions;
33 import org.apache.maven.cling.invoker.BaseParser;
34
35 public class MavenParser extends BaseParser {
36
37 @Override
38 protected List<Options> parseCliOptions(LocalContext context) throws ParserException, IOException {
39 ArrayList<Options> result = new ArrayList<>();
40
41 result.add(parseMavenCliOptions(context.parserRequest.args()));
42
43 Path mavenConfig = context.rootDirectory != null ? context.rootDirectory.resolve(".mvn/maven.config") : null;
44 if (mavenConfig != null && Files.isRegularFile(mavenConfig)) {
45 result.add(parseMavenConfigOptions(mavenConfig));
46 }
47 return result;
48 }
49
50 protected MavenOptions parseMavenCliOptions(List<String> args) throws ParserException {
51 return parseArgs(Options.SOURCE_CLI, args);
52 }
53
54 protected MavenOptions parseMavenConfigOptions(Path configFile) throws ParserException, IOException {
55 try (Stream<String> lines = Files.lines(configFile, Charset.defaultCharset())) {
56 List<String> args =
57 lines.filter(arg -> !arg.isEmpty() && !arg.startsWith("#")).toList();
58 MavenOptions options = parseArgs("maven.config", args);
59 if (options.goals().isPresent()) {
60
61 throw new ParserException("Unrecognized maven.config file entries: "
62 + options.goals().get());
63 }
64 return options;
65 }
66 }
67
68 protected MavenOptions parseArgs(String source, List<String> args) throws ParserException {
69 try {
70 return CommonsCliMavenOptions.parse(source, args.toArray(new String[0]));
71 } catch (ParseException e) {
72 throw new ParserException("Failed to parse source " + source + ": " + e.getMessage(), e.getCause());
73 }
74 }
75
76 @Override
77 protected MavenInvokerRequest getInvokerRequest(LocalContext context) {
78 return new MavenInvokerRequest(
79 context.parserRequest,
80 context.cwd,
81 context.installationDirectory,
82 context.userHomeDirectory,
83 context.userProperties,
84 context.systemProperties,
85 context.topDirectory,
86 context.rootDirectory,
87 context.parserRequest.in(),
88 context.parserRequest.out(),
89 context.parserRequest.err(),
90 context.extensions,
91 getJvmArguments(context.rootDirectory),
92 (MavenOptions) context.options);
93 }
94
95 @Override
96 @SuppressWarnings({"unchecked", "rawtypes"})
97 protected MavenOptions assembleOptions(List<Options> parsedOptions) {
98 return LayeredMavenOptions.layerMavenOptions((List) parsedOptions);
99 }
100 }