1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.cli;
20
21 import java.io.BufferedReader;
22 import java.io.Console;
23 import java.io.File;
24 import java.io.FileNotFoundException;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.PrintStream;
30 import java.nio.charset.StandardCharsets;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.util.ArrayList;
35 import java.util.Collections;
36 import java.util.HashSet;
37 import java.util.LinkedHashMap;
38 import java.util.List;
39 import java.util.ListIterator;
40 import java.util.Map;
41 import java.util.Map.Entry;
42 import java.util.Objects;
43 import java.util.Properties;
44 import java.util.ServiceLoader;
45 import java.util.Set;
46 import java.util.StringTokenizer;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
49 import java.util.stream.Stream;
50
51 import com.google.inject.AbstractModule;
52 import org.apache.commons.cli.CommandLine;
53 import org.apache.commons.cli.Option;
54 import org.apache.commons.cli.ParseException;
55 import org.apache.commons.cli.UnrecognizedOptionException;
56 import org.apache.maven.BuildAbort;
57 import org.apache.maven.InternalErrorException;
58 import org.apache.maven.Maven;
59 import org.apache.maven.api.services.MessageBuilder;
60 import org.apache.maven.building.FileSource;
61 import org.apache.maven.building.Problem;
62 import org.apache.maven.building.Source;
63 import org.apache.maven.cli.configuration.ConfigurationProcessor;
64 import org.apache.maven.cli.configuration.SettingsXmlConfigurationProcessor;
65 import org.apache.maven.cli.event.DefaultEventSpyContext;
66 import org.apache.maven.cli.event.ExecutionEventLogger;
67 import org.apache.maven.cli.internal.BootstrapCoreExtensionManager;
68 import org.apache.maven.cli.internal.extension.model.CoreExtension;
69 import org.apache.maven.cli.internal.extension.model.io.xpp3.CoreExtensionsXpp3Reader;
70 import org.apache.maven.cli.logging.Slf4jConfiguration;
71 import org.apache.maven.cli.logging.Slf4jConfigurationFactory;
72 import org.apache.maven.cli.logging.Slf4jLoggerManager;
73 import org.apache.maven.cli.logging.Slf4jStdoutLogger;
74 import org.apache.maven.cli.transfer.ConsoleMavenTransferListener;
75 import org.apache.maven.cli.transfer.QuietMavenTransferListener;
76 import org.apache.maven.cli.transfer.SimplexTransferListener;
77 import org.apache.maven.cli.transfer.Slf4jMavenTransferListener;
78 import org.apache.maven.eventspy.internal.EventSpyDispatcher;
79 import org.apache.maven.exception.DefaultExceptionHandler;
80 import org.apache.maven.exception.ExceptionHandler;
81 import org.apache.maven.exception.ExceptionSummary;
82 import org.apache.maven.execution.DefaultMavenExecutionRequest;
83 import org.apache.maven.execution.ExecutionListener;
84 import org.apache.maven.execution.MavenExecutionRequest;
85 import org.apache.maven.execution.MavenExecutionRequestPopulationException;
86 import org.apache.maven.execution.MavenExecutionRequestPopulator;
87 import org.apache.maven.execution.MavenExecutionResult;
88 import org.apache.maven.execution.scope.internal.MojoExecutionScopeModule;
89 import org.apache.maven.extension.internal.CoreExports;
90 import org.apache.maven.extension.internal.CoreExtensionEntry;
91 import org.apache.maven.jline.MessageUtils;
92 import org.apache.maven.lifecycle.LifecycleExecutionException;
93 import org.apache.maven.model.building.ModelProcessor;
94 import org.apache.maven.model.interpolation.ModelInterpolator;
95 import org.apache.maven.model.root.RootLocator;
96 import org.apache.maven.project.MavenProject;
97 import org.apache.maven.properties.internal.EnvironmentUtils;
98 import org.apache.maven.properties.internal.SystemProperties;
99 import org.apache.maven.session.scope.internal.SessionScopeModule;
100 import org.apache.maven.toolchain.building.DefaultToolchainsBuildingRequest;
101 import org.apache.maven.toolchain.building.ToolchainsBuilder;
102 import org.apache.maven.toolchain.building.ToolchainsBuildingResult;
103 import org.codehaus.plexus.ContainerConfiguration;
104 import org.codehaus.plexus.DefaultContainerConfiguration;
105 import org.codehaus.plexus.DefaultPlexusContainer;
106 import org.codehaus.plexus.PlexusConstants;
107 import org.codehaus.plexus.PlexusContainer;
108 import org.codehaus.plexus.classworlds.ClassWorld;
109 import org.codehaus.plexus.classworlds.realm.ClassRealm;
110 import org.codehaus.plexus.classworlds.realm.NoSuchRealmException;
111 import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
112 import org.codehaus.plexus.interpolation.AbstractValueSource;
113 import org.codehaus.plexus.interpolation.InterpolationException;
114 import org.codehaus.plexus.interpolation.StringSearchInterpolator;
115 import org.codehaus.plexus.logging.LoggerManager;
116 import org.codehaus.plexus.util.StringUtils;
117 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
118 import org.eclipse.aether.DefaultRepositoryCache;
119 import org.eclipse.aether.repository.RepositoryPolicy;
120 import org.eclipse.aether.transfer.TransferListener;
121 import org.slf4j.ILoggerFactory;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
124 import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
125 import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
126 import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
127 import org.sonatype.plexus.components.sec.dispatcher.SecUtil;
128 import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity;
129
130 import static org.apache.maven.cli.CLIManager.COLOR;
131 import static org.apache.maven.cli.ResolveFile.resolveFile;
132 import static org.apache.maven.jline.MessageUtils.builder;
133
134
135
136
137
138
139 public class MavenCli {
140 public static final String LOCAL_REPO_PROPERTY = "maven.repo.local";
141
142 public static final String MULTIMODULE_PROJECT_DIRECTORY = "maven.multiModuleProjectDirectory";
143
144 public static final String USER_HOME = System.getProperty("user.home");
145
146 public static final File USER_MAVEN_CONFIGURATION_HOME = new File(USER_HOME, ".m2");
147
148 public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File(USER_MAVEN_CONFIGURATION_HOME, "toolchains.xml");
149
150 public static final File DEFAULT_GLOBAL_TOOLCHAINS_FILE =
151 new File(System.getProperty("maven.conf"), "toolchains.xml");
152
153 private static final String EXT_CLASS_PATH = "maven.ext.class.path";
154
155 private static final String DOT_MVN = ".mvn";
156
157 private static final String PROJECT_EXTENSIONS_FILENAME = DOT_MVN + "/extensions.xml";
158
159 private static final File USER_EXTENSIONS_FILE = new File(USER_MAVEN_CONFIGURATION_HOME, "extensions.xml");
160
161 public static final File GLOBAL_EXTENSIONS_FILE = new File(System.getProperty("maven.conf"), "extensions.xml");
162
163 private static final String MVN_MAVEN_CONFIG = DOT_MVN + "/maven.config";
164
165
166
167
168
169
170
171 private static final String MAVEN_REPO_CENTRAL_ENV = "env.MAVEN_REPO_CENTRAL";
172
173 public static final String STYLE_COLOR_PROPERTY = "style.color";
174
175 private ClassWorld classWorld;
176
177 private LoggerManager plexusLoggerManager;
178
179 private ILoggerFactory slf4jLoggerFactory;
180
181 private Logger slf4jLogger;
182
183 private EventSpyDispatcher eventSpyDispatcher;
184
185 private ModelProcessor modelProcessor;
186
187 private Maven maven;
188
189 private MavenExecutionRequestPopulator executionRequestPopulator;
190
191 private ToolchainsBuilder toolchainsBuilder;
192
193 private DefaultSecDispatcher dispatcher;
194
195 private Map<String, ConfigurationProcessor> configurationProcessors;
196
197 private CLIManager cliManager;
198
199 private static final Pattern NEXT_LINE = Pattern.compile("\r?\n");
200
201 public MavenCli() {
202 this(null);
203 }
204
205
206 public MavenCli(ClassWorld classWorld) {
207 this.classWorld = classWorld;
208 }
209
210 public static void main(String[] args) {
211 int result = main(args, null);
212
213 System.exit(result);
214 }
215
216 public static int main(String[] args, ClassWorld classWorld) {
217 MavenCli cli = new MavenCli();
218
219 MessageUtils.systemInstall();
220 return cli.doMain(new CliRequest(args, classWorld));
221 }
222
223
224 public static int doMain(String[] args, ClassWorld classWorld) {
225 MavenCli cli = new MavenCli();
226 return cli.doMain(new CliRequest(args, classWorld));
227 }
228
229
230
231
232
233
234 public int doMain(String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr) {
235 PrintStream oldout = System.out;
236 PrintStream olderr = System.err;
237
238 final Set<String> realms;
239 if (classWorld != null) {
240 realms = new HashSet<>();
241 for (ClassRealm realm : classWorld.getRealms()) {
242 realms.add(realm.getId());
243 }
244 } else {
245 realms = Collections.emptySet();
246 }
247
248 try {
249 if (stdout != null) {
250 System.setOut(stdout);
251 }
252 if (stderr != null) {
253 System.setErr(stderr);
254 }
255
256 CliRequest cliRequest = new CliRequest(args, classWorld);
257 cliRequest.workingDirectory = workingDirectory;
258
259 return doMain(cliRequest);
260 } finally {
261 if (classWorld != null) {
262 for (ClassRealm realm : new ArrayList<>(classWorld.getRealms())) {
263 String realmId = realm.getId();
264 if (!realms.contains(realmId)) {
265 try {
266 classWorld.disposeRealm(realmId);
267 } catch (NoSuchRealmException ignored) {
268
269 }
270 }
271 }
272 }
273 System.setOut(oldout);
274 System.setErr(olderr);
275 }
276 }
277
278
279 public int doMain(CliRequest cliRequest) {
280 PlexusContainer localContainer = null;
281 try {
282 initialize(cliRequest);
283 cli(cliRequest);
284 properties(cliRequest);
285 setupGuiceClassLoading();
286 logging(cliRequest);
287 informativeCommands(cliRequest);
288 version(cliRequest);
289 localContainer = container(cliRequest);
290 commands(cliRequest);
291 configure(cliRequest);
292 toolchains(cliRequest);
293 populateRequest(cliRequest);
294 encryption(cliRequest);
295 return execute(cliRequest);
296 } catch (ExitException e) {
297 return e.exitCode;
298 } catch (UnrecognizedOptionException e) {
299
300 return 1;
301 } catch (BuildAbort e) {
302 CLIReportingUtils.showError(slf4jLogger, "ABORTED", e, cliRequest.showErrors);
303
304 return 2;
305 } catch (Exception e) {
306 CLIReportingUtils.showError(slf4jLogger, "Error executing Maven.", e, cliRequest.showErrors);
307
308 return 1;
309 } finally {
310 if (localContainer != null) {
311 localContainer.dispose();
312 }
313 }
314 }
315
316 void initialize(CliRequest cliRequest) throws ExitException {
317 if (cliRequest.workingDirectory == null) {
318 cliRequest.workingDirectory = System.getProperty("user.dir");
319 }
320
321 if (cliRequest.multiModuleProjectDirectory == null) {
322 String basedirProperty = System.getProperty(MULTIMODULE_PROJECT_DIRECTORY);
323 if (basedirProperty == null) {
324 System.err.format("-D%s system property is not set.", MULTIMODULE_PROJECT_DIRECTORY);
325 throw new ExitException(1);
326 }
327 File basedir = basedirProperty != null ? new File(basedirProperty) : new File("");
328
329
330
331
332 cliRequest.multiModuleProjectDirectory =
333 getCanonicalPath(basedir.toPath()).toFile();
334 }
335
336
337
338
339 Path topDirectory = Paths.get(cliRequest.workingDirectory);
340 boolean isAltFile = false;
341 for (String arg : cliRequest.args) {
342 if (isAltFile) {
343
344 Path path = topDirectory.resolve(stripLeadingAndTrailingQuotes(arg));
345 if (Files.isDirectory(path)) {
346 topDirectory = path;
347 } else if (Files.isRegularFile(path)) {
348 topDirectory = path.getParent();
349 if (!Files.isDirectory(topDirectory)) {
350 System.err.println("Directory " + topDirectory
351 + " extracted from the -f/--file command-line argument " + arg + " does not exist");
352 throw new ExitException(1);
353 }
354 } else {
355 System.err.println(
356 "POM file " + arg + " specified with the -f/--file command line argument does not exist");
357 throw new ExitException(1);
358 }
359 break;
360 } else {
361
362 isAltFile = arg.equals("-f") || arg.equals("--file");
363 }
364 }
365 topDirectory = getCanonicalPath(topDirectory);
366 cliRequest.request.setTopDirectory(topDirectory);
367
368
369
370
371 RootLocator rootLocator =
372 ServiceLoader.load(RootLocator.class).iterator().next();
373 cliRequest.request.setRootDirectory(rootLocator.findRoot(topDirectory));
374
375
376
377
378
379 String mavenHome = System.getProperty("maven.home");
380
381 if (mavenHome != null) {
382 System.setProperty("maven.home", new File(mavenHome).getAbsolutePath());
383 }
384 }
385
386 void cli(CliRequest cliRequest) throws Exception {
387
388
389
390
391 slf4jLogger = new Slf4jStdoutLogger();
392
393 cliManager = new CLIManager();
394
395 CommandLine mavenConfig = null;
396 try {
397 File configFile = new File(cliRequest.multiModuleProjectDirectory, MVN_MAVEN_CONFIG);
398
399 if (configFile.isFile()) {
400 try (Stream<String> lines = Files.lines(configFile.toPath(), StandardCharsets.UTF_8)) {
401 String[] args = lines.filter(arg -> !arg.isEmpty() && !arg.startsWith("#"))
402 .toArray(String[]::new);
403 mavenConfig = cliManager.parse(args);
404 List<?> unrecognized = mavenConfig.getArgList();
405 if (!unrecognized.isEmpty()) {
406
407 throw new ParseException("Unrecognized maven.config file entries: " + unrecognized);
408 }
409 }
410 }
411 } catch (ParseException e) {
412 System.err.println("Unable to parse maven.config file options: " + e.getMessage());
413 cliManager.displayHelp(System.out);
414 throw e;
415 }
416
417 try {
418 CommandLine mavenCli = cliManager.parse(cliRequest.args);
419 if (mavenConfig == null) {
420 cliRequest.commandLine = mavenCli;
421 } else {
422 cliRequest.commandLine = cliMerge(mavenConfig, mavenCli);
423 }
424 } catch (ParseException e) {
425 System.err.println("Unable to parse command line options: " + e.getMessage());
426 cliManager.displayHelp(System.out);
427 throw e;
428 }
429
430
431 try {
432 if (cliRequest.commandLine.hasOption("llr")) {
433 throw new UnrecognizedOptionException("Option '-llr' is not supported starting with Maven 3.9.1");
434 }
435 } catch (ParseException e) {
436 System.err.println("Unsupported options: " + e.getMessage());
437 cliManager.displayHelp(System.out);
438 throw e;
439 }
440 }
441
442 private void informativeCommands(CliRequest cliRequest) throws ExitException {
443 if (cliRequest.commandLine.hasOption(CLIManager.HELP)) {
444 cliManager.displayHelp(System.out);
445 throw new ExitException(0);
446 }
447
448 if (cliRequest.commandLine.hasOption(CLIManager.VERSION)) {
449 if (cliRequest.commandLine.hasOption(CLIManager.QUIET)) {
450 System.out.println(CLIReportingUtils.showVersionMinimal());
451 } else {
452 System.out.println(CLIReportingUtils.showVersion());
453 }
454 throw new ExitException(0);
455 }
456 }
457
458 private CommandLine cliMerge(CommandLine mavenConfig, CommandLine mavenCli) {
459 CommandLine.Builder commandLineBuilder = new CommandLine.Builder();
460
461
462 for (String arg : mavenCli.getArgs()) {
463 commandLineBuilder.addArg(arg);
464 }
465
466
467
468
469
470
471
472
473
474
475
476 List<Option> setPropertyOptions = new ArrayList<>();
477 for (Option opt : mavenCli.getOptions()) {
478 if (String.valueOf(CLIManager.SET_USER_PROPERTY).equals(opt.getOpt())) {
479 setPropertyOptions.add(opt);
480 } else {
481 commandLineBuilder.addOption(opt);
482 }
483 }
484 for (Option opt : mavenConfig.getOptions()) {
485 commandLineBuilder.addOption(opt);
486 }
487
488 for (Option opt : setPropertyOptions) {
489 commandLineBuilder.addOption(opt);
490 }
491 return commandLineBuilder.build();
492 }
493
494
495
496
497
498 void setupGuiceClassLoading() {
499 if (System.getProperty("guice_custom_class_loading", "").trim().isEmpty()) {
500 System.setProperty("guice_custom_class_loading", "CHILD");
501 }
502 }
503
504
505
506
507 void logging(CliRequest cliRequest) {
508
509 cliRequest.debug = cliRequest.commandLine.hasOption(CLIManager.DEBUG);
510 cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption(CLIManager.QUIET);
511 cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption(CLIManager.ERRORS);
512
513 slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
514 Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory);
515
516 if (cliRequest.debug) {
517 cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_DEBUG);
518 slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG);
519 } else if (cliRequest.quiet) {
520 cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_ERROR);
521 slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR);
522 }
523
524
525
526
527 String styleColor = cliRequest.getUserProperties().getProperty(STYLE_COLOR_PROPERTY, "auto");
528 styleColor = cliRequest.commandLine.getOptionValue(COLOR, styleColor);
529 if ("always".equals(styleColor) || "yes".equals(styleColor) || "force".equals(styleColor)) {
530 MessageUtils.setColorEnabled(true);
531 } else if ("never".equals(styleColor) || "no".equals(styleColor) || "none".equals(styleColor)) {
532 MessageUtils.setColorEnabled(false);
533 } else if (!"auto".equals(styleColor) && !"tty".equals(styleColor) && !"if-tty".equals(styleColor)) {
534 throw new IllegalArgumentException(
535 "Invalid color configuration value '" + styleColor + "'. Supported are 'auto', 'always', 'never'.");
536 } else if (cliRequest.commandLine.hasOption(CLIManager.BATCH_MODE)
537 || cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
538 MessageUtils.setColorEnabled(false);
539 } else {
540
541 MessageUtils.setColorEnabled(MessageUtils.isTty());
542 }
543
544
545 if (cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
546 File logFile = new File(cliRequest.commandLine.getOptionValue(CLIManager.LOG_FILE));
547 logFile = resolveFile(logFile, cliRequest.workingDirectory);
548
549
550 try {
551 PrintStream ps = new PrintStream(new FileOutputStream(logFile));
552 System.setOut(ps);
553 System.setErr(ps);
554 } catch (FileNotFoundException e) {
555
556
557
558 }
559 }
560 slf4jConfiguration.activate();
561
562 plexusLoggerManager = new Slf4jLoggerManager();
563 slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
564 }
565
566 private void version(CliRequest cliRequest) {
567 if (cliRequest.debug || cliRequest.commandLine.hasOption(CLIManager.SHOW_VERSION)) {
568 System.out.println(CLIReportingUtils.showVersion());
569 }
570 }
571
572 private void commands(CliRequest cliRequest) throws ExitException {
573 if (cliRequest.showErrors) {
574 slf4jLogger.info("Error stacktraces are turned on.");
575 }
576
577 if (MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals(cliRequest.request.getGlobalChecksumPolicy())) {
578 slf4jLogger.info("Disabling strict checksum verification on all artifact downloads.");
579 } else if (MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals(cliRequest.request.getGlobalChecksumPolicy())) {
580 slf4jLogger.info("Enabling strict checksum verification on all artifact downloads.");
581 }
582
583
584
585
586
587
588
589
590
591 List<String> goals = cliRequest.commandLine.getArgList();
592 if (goals.isEmpty()
593 && modelProcessor != null
594 && !cliRequest.commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)
595 && !cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_PASSWORD)
596 && !cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_MASTER_PASSWORD)) {
597 File pom = modelProcessor.locatePom(new File(cliRequest.workingDirectory));
598 if (!pom.isFile()) {
599 cliManager.displayHelp(System.out);
600 throw new ExitException(0);
601 }
602 }
603
604 if (slf4jLogger.isDebugEnabled()) {
605 slf4jLogger.debug("Message scheme: {}", (MessageUtils.isColorEnabled() ? "color" : "plain"));
606 slf4jLogger.debug("Message terminal: {}", MessageUtils.isTty() ? "ansi" : "none");
607 if (MessageUtils.isColorEnabled()) {
608 MessageBuilder buff = builder();
609 buff.a("Message styles: ");
610 buff.a(builder().trace("trace")).a(' ');
611 buff.a(builder().debug("debug")).a(' ');
612 buff.a(builder().info("info")).a(' ');
613 buff.a(builder().warning("warning")).a(' ');
614 buff.a(builder().error("error")).a(' ');
615 buff.success("success").a(' ');
616 buff.failure("failure").a(' ');
617 buff.strong("strong").a(' ');
618 buff.mojo("mojo").a(' ');
619 buff.project("project");
620 slf4jLogger.debug(buff.toString());
621 }
622 }
623 }
624
625
626
627 void properties(CliRequest cliRequest) throws ExitException {
628 try {
629 populateProperties(cliRequest, cliRequest.systemProperties, cliRequest.userProperties);
630
631 StringSearchInterpolator interpolator =
632 createInterpolator(cliRequest, cliRequest.systemProperties, cliRequest.userProperties);
633 CommandLine.Builder commandLineBuilder = new CommandLine.Builder();
634 for (Option option : cliRequest.commandLine.getOptions()) {
635 if (!String.valueOf(CLIManager.SET_USER_PROPERTY).equals(option.getOpt())) {
636 List<String> values = option.getValuesList();
637 for (ListIterator<String> it = values.listIterator(); it.hasNext(); ) {
638 it.set(interpolator.interpolate(it.next()));
639 }
640 }
641 commandLineBuilder.addOption(option);
642 }
643 for (String arg : cliRequest.commandLine.getArgList()) {
644 commandLineBuilder.addArg(interpolator.interpolate(arg));
645 }
646 cliRequest.commandLine = commandLineBuilder.build();
647 } catch (InterpolationException e) {
648 String message = "ERROR: Could not interpolate properties and/or arguments: " + e.getMessage();
649 System.err.println(message);
650 throw new ExitException(1);
651 } catch (IllegalUseOfUndefinedProperty e) {
652 String message = "ERROR: Illegal use of undefined property: " + e.property;
653 System.err.println(message);
654 try {
655 cliRequest.request.getRootDirectory();
656 } catch (IllegalStateException ex) {
657 System.err.println();
658 System.err.println(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE);
659 }
660 throw new ExitException(1);
661 }
662 }
663
664 PlexusContainer container(CliRequest cliRequest) throws Exception {
665 if (cliRequest.classWorld == null) {
666 cliRequest.classWorld =
667 new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
668 }
669
670 ClassRealm coreRealm = cliRequest.classWorld.getClassRealm("plexus.core");
671 if (coreRealm == null) {
672 coreRealm = cliRequest.classWorld.getRealms().iterator().next();
673 }
674
675 List<File> extClassPath = parseExtClasspath(cliRequest);
676
677 CoreExtensionEntry coreEntry = CoreExtensionEntry.discoverFrom(coreRealm);
678 List<CoreExtensionEntry> extensions =
679 loadCoreExtensions(cliRequest, coreRealm, coreEntry.getExportedArtifacts());
680
681 ClassRealm containerRealm = setupContainerRealm(cliRequest.classWorld, coreRealm, extClassPath, extensions);
682
683 ContainerConfiguration cc = new DefaultContainerConfiguration()
684 .setClassWorld(cliRequest.classWorld)
685 .setRealm(containerRealm)
686 .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
687 .setAutoWiring(true)
688 .setJSR250Lifecycle(true)
689 .setVisibilityPredicateSupplierTransformer(s -> () -> {
690 if (BootstrapCoreExtensionManager.isContextRealmCoreExtensionRealm()) {
691 return null;
692 } else {
693 return s.get();
694 }
695 })
696 .setName("maven");
697
698 Set<String> exportedArtifacts = new HashSet<>(coreEntry.getExportedArtifacts());
699 Set<String> exportedPackages = new HashSet<>(coreEntry.getExportedPackages());
700 for (CoreExtensionEntry extension : extensions) {
701 exportedArtifacts.addAll(extension.getExportedArtifacts());
702 exportedPackages.addAll(extension.getExportedPackages());
703 }
704
705 final CoreExports exports = new CoreExports(containerRealm, exportedArtifacts, exportedPackages);
706
707 DefaultPlexusContainer container = new DefaultPlexusContainer(cc, new AbstractModule() {
708 @Override
709 protected void configure() {
710 bind(ILoggerFactory.class).toInstance(slf4jLoggerFactory);
711 bind(CoreExports.class).toInstance(exports);
712 }
713 });
714
715
716 container.setLookupRealm(null);
717 Thread.currentThread().setContextClassLoader(container.getContainerRealm());
718
719 container.setLoggerManager(plexusLoggerManager);
720
721 for (CoreExtensionEntry extension : extensions) {
722 container.discoverComponents(
723 extension.getClassRealm(),
724 new SessionScopeModule(container),
725 new MojoExecutionScopeModule(container));
726 }
727
728 customizeContainer(container);
729
730 container.getLoggerManager().setThresholds(cliRequest.request.getLoggingLevel());
731
732 eventSpyDispatcher = container.lookup(EventSpyDispatcher.class);
733
734 DefaultEventSpyContext eventSpyContext = new DefaultEventSpyContext();
735 Map<String, Object> data = eventSpyContext.getData();
736 data.put("plexus", container);
737 data.put("workingDirectory", cliRequest.workingDirectory);
738 data.put("systemProperties", cliRequest.systemProperties);
739 data.put("userProperties", cliRequest.userProperties);
740 data.put("versionProperties", CLIReportingUtils.getBuildProperties());
741 eventSpyDispatcher.init(eventSpyContext);
742
743
744 slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
745
746 maven = container.lookup(Maven.class);
747
748 executionRequestPopulator = container.lookup(MavenExecutionRequestPopulator.class);
749
750 modelProcessor = createModelProcessor(container);
751
752 configurationProcessors = container.lookupMap(ConfigurationProcessor.class);
753
754 toolchainsBuilder = container.lookup(ToolchainsBuilder.class);
755
756 dispatcher = (DefaultSecDispatcher) container.lookup(SecDispatcher.class, "maven");
757
758 return container;
759 }
760
761 private List<CoreExtensionEntry> loadCoreExtensions(
762 CliRequest cliRequest, ClassRealm containerRealm, Set<String> providedArtifacts) throws Exception {
763 if (cliRequest.multiModuleProjectDirectory == null) {
764 return Collections.emptyList();
765 }
766
767 File projectExtensionsFile = new File(cliRequest.multiModuleProjectDirectory, PROJECT_EXTENSIONS_FILENAME);
768 if (!projectExtensionsFile.isFile() && !USER_EXTENSIONS_FILE.isFile() && !GLOBAL_EXTENSIONS_FILE.isFile()) {
769 return Collections.emptyList();
770 }
771
772 List<CoreExtension> projectExtensions = null;
773 List<CoreExtension> userExtensions = null;
774 List<CoreExtension> globalExtensions = null;
775 if (projectExtensionsFile.isFile()) {
776 projectExtensions = readCoreExtensionsDescriptor(projectExtensionsFile.toPath());
777 }
778 if (USER_EXTENSIONS_FILE.isFile()) {
779 userExtensions = readCoreExtensionsDescriptor(USER_EXTENSIONS_FILE.toPath());
780 }
781 if (GLOBAL_EXTENSIONS_FILE.isFile()) {
782 globalExtensions = readCoreExtensionsDescriptor(GLOBAL_EXTENSIONS_FILE.toPath());
783 }
784
785 if ((projectExtensions == null || projectExtensions.isEmpty())
786 && (userExtensions == null || userExtensions.isEmpty())
787 && (globalExtensions == null || globalExtensions.isEmpty())) {
788 return Collections.emptyList();
789 }
790
791 Map<Path, List<CoreExtension>> configuredCoreExtensions = new LinkedHashMap<>();
792 if (projectExtensions != null && !projectExtensions.isEmpty()) {
793 configuredCoreExtensions.put(projectExtensionsFile.toPath(), projectExtensions);
794 }
795 if (userExtensions != null && !userExtensions.isEmpty()) {
796 configuredCoreExtensions.put(USER_EXTENSIONS_FILE.toPath(), userExtensions);
797 }
798 if (globalExtensions != null && !globalExtensions.isEmpty()) {
799 configuredCoreExtensions.put(GLOBAL_EXTENSIONS_FILE.toPath(), globalExtensions);
800 }
801
802 List<CoreExtension> extensions = selectCoreExtensions(configuredCoreExtensions);
803
804 ContainerConfiguration cc = new DefaultContainerConfiguration()
805 .setClassWorld(cliRequest.classWorld)
806 .setRealm(containerRealm)
807 .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
808 .setAutoWiring(true)
809 .setJSR250Lifecycle(true)
810 .setName("maven");
811
812 DefaultPlexusContainer container = new DefaultPlexusContainer(cc, new AbstractModule() {
813 @Override
814 protected void configure() {
815 bind(ILoggerFactory.class).toInstance(slf4jLoggerFactory);
816 }
817 });
818
819 try {
820 container.setLookupRealm(null);
821
822 container.setLoggerManager(plexusLoggerManager);
823
824 container.getLoggerManager().setThresholds(cliRequest.request.getLoggingLevel());
825
826 Thread.currentThread().setContextClassLoader(container.getContainerRealm());
827
828 executionRequestPopulator = container.lookup(MavenExecutionRequestPopulator.class);
829
830 configurationProcessors = container.lookupMap(ConfigurationProcessor.class);
831
832 configure(cliRequest);
833
834 MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(cliRequest.request);
835
836 request = populateRequest(cliRequest, request);
837
838 request = executionRequestPopulator.populateDefaults(request);
839
840 BootstrapCoreExtensionManager resolver = container.lookup(BootstrapCoreExtensionManager.class);
841
842 return Collections.unmodifiableList(resolver.loadCoreExtensions(request, providedArtifacts, extensions));
843
844 } finally {
845 executionRequestPopulator = null;
846 container.dispose();
847 }
848 }
849
850 List<CoreExtension> readCoreExtensionsDescriptor(Path extensionsFile) throws IOException {
851 CoreExtensionsXpp3Reader parser = new CoreExtensionsXpp3Reader();
852 try (BufferedReader is = Files.newBufferedReader(extensionsFile, StandardCharsets.UTF_8)) {
853 return parser.read(is).getExtensions();
854 } catch (IOException | XmlPullParserException e) {
855 throw new IOException(
856 "Unable to parse core extensions descriptor " + extensionsFile + ": " + e.getMessage(), e);
857 }
858 }
859
860 private List<CoreExtension> selectCoreExtensions(Map<Path, List<CoreExtension>> configuredCoreExtensions) {
861 slf4jLogger.debug("Configured core extensions (in precedence order):");
862 for (Map.Entry<Path, List<CoreExtension>> source : configuredCoreExtensions.entrySet()) {
863 slf4jLogger.debug("* Source file: {}", source.getKey());
864 for (CoreExtension extension : source.getValue()) {
865 slf4jLogger.debug(" - {} -> {}", extension.getId(), source.getKey());
866 }
867 }
868
869 LinkedHashMap<String, CoreExtension> selectedExtensions = new LinkedHashMap<>();
870 List<String> conflicts = new ArrayList<>();
871 for (Map.Entry<Path, List<CoreExtension>> coreExtensions : configuredCoreExtensions.entrySet()) {
872 for (CoreExtension coreExtension : coreExtensions.getValue()) {
873 String key = coreExtension.getGroupId() + ":" + coreExtension.getArtifactId();
874 CoreExtension conflict = selectedExtensions.putIfAbsent(key, coreExtension);
875 if (conflict != null && !Objects.equals(coreExtension.getVersion(), conflict.getVersion())) {
876 conflicts.add(String.format(
877 "Conflicting extension %s: %s vs %s in %s",
878 key, coreExtension.getVersion(), conflict.getVersion(), coreExtensions.getKey()));
879 }
880 }
881 }
882 if (!conflicts.isEmpty()) {
883 slf4jLogger.warn("Found {} extension conflict(s):", conflicts.size());
884 for (String conflict : conflicts) {
885 slf4jLogger.warn("* {}", conflict);
886 }
887 slf4jLogger.warn("");
888 slf4jLogger.warn(
889 "Order of core extensions precedence is project > user > installation. Selected extensions are:");
890 for (CoreExtension extension : selectedExtensions.values()) {
891 slf4jLogger.warn("* {}", extension.getId());
892 }
893 }
894
895 slf4jLogger.debug("Selected core extensions (in loading order):");
896 for (CoreExtension source : selectedExtensions.values()) {
897 slf4jLogger.debug("* {}: ", source.getId());
898 }
899 return new ArrayList<>(selectedExtensions.values());
900 }
901
902 private ClassRealm setupContainerRealm(
903 ClassWorld classWorld, ClassRealm coreRealm, List<File> extClassPath, List<CoreExtensionEntry> extensions)
904 throws Exception {
905 if (!extClassPath.isEmpty() || !extensions.isEmpty()) {
906 ClassRealm extRealm = classWorld.newRealm("maven.ext", null);
907
908 extRealm.setParentRealm(coreRealm);
909
910 slf4jLogger.debug("Populating class realm {}", extRealm.getId());
911
912 for (File file : extClassPath) {
913 slf4jLogger.debug(" Included {}", file);
914
915 extRealm.addURL(file.toURI().toURL());
916 }
917
918 for (CoreExtensionEntry entry : reverse(extensions)) {
919 Set<String> exportedPackages = entry.getExportedPackages();
920 ClassRealm realm = entry.getClassRealm();
921 for (String exportedPackage : exportedPackages) {
922 extRealm.importFrom(realm, exportedPackage);
923 }
924 if (exportedPackages.isEmpty()) {
925
926 extRealm.importFrom(realm, realm.getId());
927 }
928 }
929
930 return extRealm;
931 }
932
933 return coreRealm;
934 }
935
936 private static <T> List<T> reverse(List<T> list) {
937 List<T> copy = new ArrayList<>(list);
938 Collections.reverse(copy);
939 return copy;
940 }
941
942 private List<File> parseExtClasspath(CliRequest cliRequest) {
943 String extClassPath = cliRequest.userProperties.getProperty(EXT_CLASS_PATH);
944 if (extClassPath == null) {
945 extClassPath = cliRequest.systemProperties.getProperty(EXT_CLASS_PATH);
946 }
947
948 List<File> jars = new ArrayList<>();
949
950 if (StringUtils.isNotEmpty(extClassPath)) {
951 for (String jar : StringUtils.split(extClassPath, File.pathSeparator)) {
952 File file = resolveFile(new File(jar), cliRequest.workingDirectory);
953
954 slf4jLogger.debug(" Included {}", file);
955
956 jars.add(file);
957 }
958 }
959
960 return jars;
961 }
962
963
964
965
966
967
968
969
970
971
972
973
974
975 static String readPassword(Console console, InputStream in, String prompt) throws IOException {
976 String password;
977 if (console != null) {
978 char[] chars = console.readPassword(prompt);
979 password = (chars == null) ? null : String.copyValueOf(chars);
980
981 if (chars != null) {
982
983 java.util.Arrays.fill(chars, ' ');
984 }
985 } else {
986
987 password = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)).readLine();
988 }
989
990 if (password == null || password.isEmpty()) {
991 throw new IllegalStateException("No password was provided");
992 }
993
994 return password;
995 }
996
997
998
999
1000 private void encryption(CliRequest cliRequest) throws Exception {
1001 if (cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_MASTER_PASSWORD)) {
1002 String passwd = cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_MASTER_PASSWORD);
1003
1004 if (passwd == null) {
1005 passwd = readPassword(System.console(), System.in, "Master password: ");
1006 }
1007
1008 DefaultPlexusCipher cipher = new DefaultPlexusCipher();
1009
1010 System.out.println(cipher.encryptAndDecorate(passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION));
1011
1012 throw new ExitException(0);
1013 } else if (cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_PASSWORD)) {
1014 String passwd = cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_PASSWORD);
1015
1016 if (passwd == null) {
1017 passwd = readPassword(System.console(), System.in, "Password: ");
1018 }
1019
1020 String configurationFile = dispatcher.getConfigurationFile();
1021
1022 if (configurationFile.startsWith("~")) {
1023 configurationFile = System.getProperty("user.home") + configurationFile.substring(1);
1024 }
1025
1026 String file = System.getProperty(DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile);
1027
1028 String master = null;
1029
1030 SettingsSecurity sec = SecUtil.read(file, true);
1031 if (sec != null) {
1032 master = sec.getMaster();
1033 }
1034
1035 if (master == null) {
1036 throw new IllegalStateException("Master password is not set in the setting security file: " + file);
1037 }
1038
1039 DefaultPlexusCipher cipher = new DefaultPlexusCipher();
1040 String masterPasswd = cipher.decryptDecorated(master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION);
1041 System.out.println(cipher.encryptAndDecorate(passwd, masterPasswd));
1042
1043 throw new ExitException(0);
1044 }
1045 }
1046
1047 private int execute(CliRequest cliRequest) throws MavenExecutionRequestPopulationException {
1048 MavenExecutionRequest request = executionRequestPopulator.populateDefaults(cliRequest.request);
1049 request.setRepositoryCache(new DefaultRepositoryCache());
1050
1051 eventSpyDispatcher.onEvent(request);
1052
1053 MavenExecutionResult result = maven.execute(request);
1054
1055 eventSpyDispatcher.onEvent(result);
1056
1057 eventSpyDispatcher.close();
1058
1059 if (result.hasExceptions()) {
1060 ExceptionHandler handler = new DefaultExceptionHandler();
1061
1062 Map<String, String> references = new LinkedHashMap<>();
1063
1064 MavenProject project = null;
1065
1066 for (Throwable exception : result.getExceptions()) {
1067 ExceptionSummary summary = handler.handleException(exception);
1068
1069 logSummary(summary, references, "", cliRequest.showErrors);
1070
1071 if (project == null && exception instanceof LifecycleExecutionException) {
1072 project = ((LifecycleExecutionException) exception).getProject();
1073 }
1074 }
1075
1076 slf4jLogger.error("");
1077
1078 if (!cliRequest.showErrors) {
1079 slf4jLogger.error(
1080 "To see the full stack trace of the errors, re-run Maven with the {} switch.",
1081 builder().strong("-e"));
1082 }
1083 if (!slf4jLogger.isDebugEnabled()) {
1084 slf4jLogger.error(
1085 "Re-run Maven using the {} switch to enable full debug logging.",
1086 builder().strong("-X"));
1087 }
1088
1089 if (!references.isEmpty()) {
1090 slf4jLogger.error("");
1091 slf4jLogger.error("For more information about the errors and possible solutions"
1092 + ", please read the following articles:");
1093
1094 for (Map.Entry<String, String> entry : references.entrySet()) {
1095 slf4jLogger.error("{} {}", builder().strong(entry.getValue()), entry.getKey());
1096 }
1097 }
1098
1099 if (project != null
1100 && !project.equals(result.getTopologicallySortedProjects().get(0))) {
1101 slf4jLogger.error("");
1102 slf4jLogger.error("After correcting the problems, you can resume the build with the command");
1103 slf4jLogger.error(builder()
1104 .a(" ")
1105 .strong("mvn <args> -rf " + getResumeFrom(result.getTopologicallySortedProjects(), project))
1106 .toString());
1107 }
1108
1109 if (MavenExecutionRequest.REACTOR_FAIL_NEVER.equals(cliRequest.request.getReactorFailureBehavior())) {
1110 slf4jLogger.info("Build failures were ignored.");
1111
1112 return 0;
1113 } else {
1114 return 1;
1115 }
1116 } else {
1117 return 0;
1118 }
1119 }
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137 private String getResumeFrom(List<MavenProject> mavenProjects, MavenProject failedProject) {
1138 for (MavenProject buildProject : mavenProjects) {
1139 if (failedProject.getArtifactId().equals(buildProject.getArtifactId())
1140 && !failedProject.equals(buildProject)) {
1141 return failedProject.getGroupId() + ":" + failedProject.getArtifactId();
1142 }
1143 }
1144 return ":" + failedProject.getArtifactId();
1145 }
1146
1147 private void logSummary(
1148 ExceptionSummary summary, Map<String, String> references, String indent, boolean showErrors) {
1149 String referenceKey = "";
1150
1151 if (StringUtils.isNotEmpty(summary.getReference())) {
1152 referenceKey = references.get(summary.getReference());
1153 if (referenceKey == null) {
1154 referenceKey = "[Help " + (references.size() + 1) + "]";
1155 references.put(summary.getReference(), referenceKey);
1156 }
1157 }
1158
1159 String msg = summary.getMessage();
1160
1161 if (StringUtils.isNotEmpty(referenceKey)) {
1162 if (msg.indexOf('\n') < 0) {
1163 msg += " -> " + builder().strong(referenceKey);
1164 } else {
1165 msg += "\n-> " + builder().strong(referenceKey);
1166 }
1167 }
1168
1169 String[] lines = NEXT_LINE.split(msg);
1170 String currentColor = "";
1171
1172 for (int i = 0; i < lines.length; i++) {
1173
1174 String line = currentColor + lines[i];
1175
1176
1177 Matcher matcher = LAST_ANSI_SEQUENCE.matcher(line);
1178 String nextColor = "";
1179 if (matcher.find()) {
1180 nextColor = matcher.group(1);
1181 if (ANSI_RESET.equals(nextColor)) {
1182
1183 nextColor = "";
1184 }
1185 }
1186
1187
1188 line = indent + line + ("".equals(nextColor) ? "" : ANSI_RESET);
1189
1190 if ((i == lines.length - 1) && (showErrors || (summary.getException() instanceof InternalErrorException))) {
1191 slf4jLogger.error(line, summary.getException());
1192 } else {
1193 slf4jLogger.error(line);
1194 }
1195
1196 currentColor = nextColor;
1197 }
1198
1199 indent += " ";
1200
1201 for (ExceptionSummary child : summary.getChildren()) {
1202 logSummary(child, references, indent, showErrors);
1203 }
1204 }
1205
1206 private static final Pattern LAST_ANSI_SEQUENCE = Pattern.compile("(\u001B\\[[;\\d]*[ -/]*[@-~])[^\u001B]*$");
1207
1208 private static final String ANSI_RESET = "\u001B\u005Bm";
1209
1210 private void configure(CliRequest cliRequest) throws Exception {
1211
1212
1213
1214
1215
1216
1217 cliRequest.request.setEventSpyDispatcher(eventSpyDispatcher);
1218
1219
1220
1221
1222
1223
1224
1225
1226 int userSuppliedConfigurationProcessorCount = configurationProcessors.size() - 1;
1227
1228 if (userSuppliedConfigurationProcessorCount == 0) {
1229
1230
1231
1232
1233 configurationProcessors.get(SettingsXmlConfigurationProcessor.HINT).process(cliRequest);
1234 } else if (userSuppliedConfigurationProcessorCount == 1) {
1235
1236
1237
1238 for (Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet()) {
1239 String hint = entry.getKey();
1240 if (!hint.equals(SettingsXmlConfigurationProcessor.HINT)) {
1241 ConfigurationProcessor configurationProcessor = entry.getValue();
1242 configurationProcessor.process(cliRequest);
1243 }
1244 }
1245 } else if (userSuppliedConfigurationProcessorCount > 1) {
1246
1247
1248
1249 StringBuilder sb = new StringBuilder(String.format(
1250 "\nThere can only be one user supplied ConfigurationProcessor, there are %s:\n\n",
1251 userSuppliedConfigurationProcessorCount));
1252 for (Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet()) {
1253 String hint = entry.getKey();
1254 if (!hint.equals(SettingsXmlConfigurationProcessor.HINT)) {
1255 ConfigurationProcessor configurationProcessor = entry.getValue();
1256 sb.append(String.format(
1257 "%s\n", configurationProcessor.getClass().getName()));
1258 }
1259 }
1260 sb.append("\n");
1261 throw new Exception(sb.toString());
1262 }
1263 }
1264
1265 void toolchains(CliRequest cliRequest) throws Exception {
1266 File userToolchainsFile;
1267
1268 if (cliRequest.commandLine.hasOption(CLIManager.ALTERNATE_USER_TOOLCHAINS)) {
1269 userToolchainsFile = new File(cliRequest.commandLine.getOptionValue(CLIManager.ALTERNATE_USER_TOOLCHAINS));
1270 userToolchainsFile = resolveFile(userToolchainsFile, cliRequest.workingDirectory);
1271
1272 if (!userToolchainsFile.isFile()) {
1273 throw new FileNotFoundException(
1274 "The specified user toolchains file does not exist: " + userToolchainsFile);
1275 }
1276 } else {
1277 userToolchainsFile = DEFAULT_USER_TOOLCHAINS_FILE;
1278 }
1279
1280 File globalToolchainsFile;
1281
1282 if (cliRequest.commandLine.hasOption(CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS)) {
1283 globalToolchainsFile =
1284 new File(cliRequest.commandLine.getOptionValue(CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS));
1285 globalToolchainsFile = resolveFile(globalToolchainsFile, cliRequest.workingDirectory);
1286
1287 if (!globalToolchainsFile.isFile()) {
1288 throw new FileNotFoundException(
1289 "The specified global toolchains file does not exist: " + globalToolchainsFile);
1290 }
1291 } else {
1292 globalToolchainsFile = DEFAULT_GLOBAL_TOOLCHAINS_FILE;
1293 }
1294
1295 cliRequest.request.setGlobalToolchainsFile(globalToolchainsFile);
1296 cliRequest.request.setUserToolchainsFile(userToolchainsFile);
1297
1298 DefaultToolchainsBuildingRequest toolchainsRequest = new DefaultToolchainsBuildingRequest();
1299 if (globalToolchainsFile.isFile()) {
1300 toolchainsRequest.setGlobalToolchainsSource(new FileSource(globalToolchainsFile));
1301 }
1302 if (userToolchainsFile.isFile()) {
1303 toolchainsRequest.setUserToolchainsSource(new FileSource(userToolchainsFile));
1304 }
1305
1306 eventSpyDispatcher.onEvent(toolchainsRequest);
1307
1308 slf4jLogger.debug(
1309 "Reading global toolchains from {}",
1310 getLocation(toolchainsRequest.getGlobalToolchainsSource(), globalToolchainsFile));
1311 slf4jLogger.debug(
1312 "Reading user toolchains from {}",
1313 getLocation(toolchainsRequest.getUserToolchainsSource(), userToolchainsFile));
1314
1315 ToolchainsBuildingResult toolchainsResult = toolchainsBuilder.build(toolchainsRequest);
1316
1317 eventSpyDispatcher.onEvent(toolchainsResult);
1318
1319 executionRequestPopulator.populateFromToolchains(cliRequest.request, toolchainsResult.getEffectiveToolchains());
1320
1321 if (!toolchainsResult.getProblems().isEmpty() && slf4jLogger.isWarnEnabled()) {
1322 slf4jLogger.warn("");
1323 slf4jLogger.warn("Some problems were encountered while building the effective toolchains");
1324
1325 for (Problem problem : toolchainsResult.getProblems()) {
1326 slf4jLogger.warn("{} @ {}", problem.getMessage(), problem.getLocation());
1327 }
1328
1329 slf4jLogger.warn("");
1330 }
1331 }
1332
1333 private Object getLocation(Source source, File defaultLocation) {
1334 if (source != null) {
1335 return source.getLocation();
1336 }
1337 return defaultLocation;
1338 }
1339
1340 private MavenExecutionRequest populateRequest(CliRequest cliRequest) {
1341 return populateRequest(cliRequest, cliRequest.request);
1342 }
1343
1344 @SuppressWarnings("checkstyle:methodlength")
1345 private MavenExecutionRequest populateRequest(CliRequest cliRequest, MavenExecutionRequest request) {
1346 CommandLine commandLine = cliRequest.commandLine;
1347 String workingDirectory = cliRequest.workingDirectory;
1348 boolean quiet = cliRequest.quiet;
1349 boolean showErrors = cliRequest.showErrors;
1350
1351 String[] deprecatedOptions = {"up", "npu", "cpu", "npr"};
1352 for (String deprecatedOption : deprecatedOptions) {
1353 if (commandLine.hasOption(deprecatedOption)) {
1354 slf4jLogger.warn(
1355 "Command line option -{} is deprecated and will be removed in future Maven versions.",
1356 deprecatedOption);
1357 }
1358 }
1359
1360
1361
1362
1363
1364
1365 if (commandLine.hasOption(CLIManager.BATCH_MODE)) {
1366 request.setInteractiveMode(false);
1367 }
1368
1369 boolean noSnapshotUpdates = false;
1370 if (commandLine.hasOption(CLIManager.SUPRESS_SNAPSHOT_UPDATES)) {
1371 noSnapshotUpdates = true;
1372 }
1373
1374 boolean updateSnapshots = false;
1375 if (commandLine.hasOption(CLIManager.UPDATE_SNAPSHOTS)) {
1376 updateSnapshots = true;
1377 }
1378
1379 String artifactsUpdatePolicy = null;
1380 String metadataUpdatePolicy = null;
1381 if (commandLine.hasOption(CLIManager.UPDATE_ARTIFACTS)) {
1382 artifactsUpdatePolicy = RepositoryPolicy.UPDATE_POLICY_ALWAYS;
1383 }
1384 if (artifactsUpdatePolicy == null && commandLine.hasOption(CLIManager.ARTIFACTS_UPDATE_POLICY)) {
1385 artifactsUpdatePolicy = commandLine.getOptionValue(CLIManager.ARTIFACTS_UPDATE_POLICY);
1386 }
1387 if (commandLine.hasOption(CLIManager.UPDATE_METADATA)) {
1388 metadataUpdatePolicy = RepositoryPolicy.UPDATE_POLICY_ALWAYS;
1389 }
1390 if (metadataUpdatePolicy == null && commandLine.hasOption(CLIManager.METADATA_UPDATE_POLICY)) {
1391 metadataUpdatePolicy = commandLine.getOptionValue(CLIManager.METADATA_UPDATE_POLICY);
1392 }
1393
1394
1395
1396
1397
1398 List<String> goals = commandLine.getArgList();
1399
1400 boolean recursive = true;
1401
1402
1403 String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
1404
1405 if (commandLine.hasOption(CLIManager.NON_RECURSIVE)) {
1406 recursive = false;
1407 }
1408
1409 if (commandLine.hasOption(CLIManager.FAIL_FAST)) {
1410 reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
1411 } else if (commandLine.hasOption(CLIManager.FAIL_AT_END)) {
1412 reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
1413 } else if (commandLine.hasOption(CLIManager.FAIL_NEVER)) {
1414 reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
1415 }
1416
1417 if (commandLine.hasOption(CLIManager.OFFLINE)) {
1418 request.setOffline(true);
1419 }
1420
1421 String globalChecksumPolicy = null;
1422
1423 if (commandLine.hasOption(CLIManager.CHECKSUM_FAILURE_POLICY)) {
1424 globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
1425 } else if (commandLine.hasOption(CLIManager.CHECKSUM_WARNING_POLICY)) {
1426 globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
1427 }
1428
1429 File baseDirectory = new File(workingDirectory, "").getAbsoluteFile();
1430
1431
1432
1433
1434
1435 List<String> activeProfiles = new ArrayList<>();
1436
1437 List<String> inactiveProfiles = new ArrayList<>();
1438
1439 performProfileActivation(commandLine, activeProfiles, inactiveProfiles);
1440
1441 TransferListener transferListener;
1442
1443 if (quiet || cliRequest.commandLine.hasOption(CLIManager.NO_TRANSFER_PROGRESS)) {
1444 transferListener = new QuietMavenTransferListener();
1445 } else if (request.isInteractiveMode() && !cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
1446
1447
1448
1449
1450 transferListener = getConsoleTransferListener(cliRequest.commandLine.hasOption(CLIManager.DEBUG));
1451 } else {
1452 transferListener = getBatchTransferListener();
1453 }
1454
1455 ExecutionListener executionListener = new ExecutionEventLogger();
1456 if (eventSpyDispatcher != null) {
1457 executionListener = eventSpyDispatcher.chainListener(executionListener);
1458 }
1459
1460 String alternatePomFile = null;
1461 if (commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)) {
1462 alternatePomFile = commandLine.getOptionValue(CLIManager.ALTERNATE_POM_FILE);
1463 }
1464
1465 request.setBaseDirectory(baseDirectory)
1466 .setGoals(goals)
1467 .setSystemProperties(cliRequest.systemProperties)
1468 .setUserProperties(cliRequest.userProperties)
1469 .setReactorFailureBehavior(reactorFailureBehaviour)
1470 .setRecursive(recursive)
1471 .setShowErrors(showErrors)
1472 .addActiveProfiles(activeProfiles)
1473 .addInactiveProfiles(inactiveProfiles)
1474 .setExecutionListener(executionListener)
1475 .setTransferListener(transferListener)
1476 .setUpdateSnapshots(updateSnapshots)
1477 .setNoSnapshotUpdates(noSnapshotUpdates)
1478 .setArtifactsUpdatePolicy(artifactsUpdatePolicy)
1479 .setMetadataUpdatePolicy(metadataUpdatePolicy)
1480 .setGlobalChecksumPolicy(globalChecksumPolicy)
1481 .setMultiModuleProjectDirectory(cliRequest.multiModuleProjectDirectory);
1482
1483 if (alternatePomFile != null) {
1484 File pom = resolveFile(new File(alternatePomFile), workingDirectory);
1485 if (pom.isDirectory()) {
1486 pom = new File(pom, "pom.xml");
1487 }
1488
1489 request.setPom(pom);
1490 } else if (modelProcessor != null) {
1491 File pom = modelProcessor.locatePom(baseDirectory);
1492
1493 if (pom.isFile()) {
1494 request.setPom(pom);
1495 }
1496 }
1497
1498 if ((request.getPom() != null) && (request.getPom().getParentFile() != null)) {
1499 request.setBaseDirectory(request.getPom().getParentFile());
1500 }
1501
1502 if (commandLine.hasOption(CLIManager.RESUME_FROM)) {
1503 request.setResumeFrom(commandLine.getOptionValue(CLIManager.RESUME_FROM));
1504 }
1505
1506 if (commandLine.hasOption(CLIManager.PROJECT_LIST)) {
1507 String[] projectOptionValues = commandLine.getOptionValues(CLIManager.PROJECT_LIST);
1508
1509 List<String> inclProjects = new ArrayList<>();
1510 List<String> exclProjects = new ArrayList<>();
1511
1512 if (projectOptionValues != null) {
1513 for (String projectOptionValue : projectOptionValues) {
1514 StringTokenizer projectTokens = new StringTokenizer(projectOptionValue, ",");
1515
1516 while (projectTokens.hasMoreTokens()) {
1517 String projectAction = projectTokens.nextToken().trim();
1518
1519 if (projectAction.startsWith("-") || projectAction.startsWith("!")) {
1520 exclProjects.add(projectAction.substring(1));
1521 } else if (projectAction.startsWith("+")) {
1522 inclProjects.add(projectAction.substring(1));
1523 } else {
1524 inclProjects.add(projectAction);
1525 }
1526 }
1527 }
1528 }
1529
1530 request.setSelectedProjects(inclProjects);
1531 request.setExcludedProjects(exclProjects);
1532 }
1533
1534 if (commandLine.hasOption(CLIManager.ALSO_MAKE) && !commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
1535 request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
1536 } else if (!commandLine.hasOption(CLIManager.ALSO_MAKE)
1537 && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
1538 request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
1539 } else if (commandLine.hasOption(CLIManager.ALSO_MAKE)
1540 && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
1541 request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_BOTH);
1542 }
1543
1544 String localRepoProperty = request.getUserProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
1545
1546
1547
1548 if (localRepoProperty == null) {
1549 localRepoProperty = request.getSystemProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
1550 }
1551
1552 if (localRepoProperty != null) {
1553 request.setLocalRepositoryPath(localRepoProperty);
1554 }
1555
1556 request.setCacheNotFound(true);
1557 request.setCacheTransferError(false);
1558 request.setIgnoreTransitiveRepositories(commandLine.hasOption(CLIManager.IGNORE_TRANSITIVE_REPOSITORIES));
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568 final String threadConfiguration =
1569 commandLine.hasOption(CLIManager.THREADS) ? commandLine.getOptionValue(CLIManager.THREADS) : null;
1570
1571 if (threadConfiguration != null) {
1572 int degreeOfConcurrency = calculateDegreeOfConcurrency(threadConfiguration);
1573 if (degreeOfConcurrency > 1) {
1574 request.setBuilderId("multithreaded");
1575 request.setDegreeOfConcurrency(degreeOfConcurrency);
1576 }
1577 }
1578
1579
1580
1581
1582 if (commandLine.hasOption(CLIManager.BUILDER)) {
1583 request.setBuilderId(commandLine.getOptionValue(CLIManager.BUILDER));
1584 }
1585
1586 return request;
1587 }
1588
1589 int calculateDegreeOfConcurrency(String originalThreadConfiguration) {
1590 String threadConfiguration = originalThreadConfiguration.trim();
1591 if (threadConfiguration.endsWith("C")) {
1592 threadConfiguration = threadConfiguration.substring(0, threadConfiguration.length() - 1);
1593
1594 try {
1595 float coreMultiplier = Float.parseFloat(threadConfiguration);
1596
1597 if (coreMultiplier <= 0.0f) {
1598 throw new IllegalArgumentException("Invalid threads core multiplier value: '" + threadConfiguration
1599 + "C'. Value must be positive.");
1600 }
1601
1602 int procs = Runtime.getRuntime().availableProcessors();
1603 int threads = (int) (coreMultiplier * procs);
1604 return threads == 0 ? 1 : threads;
1605 } catch (NumberFormatException e) {
1606 throw new IllegalArgumentException(
1607 "Invalid threads core multiplier value: '" + threadConfiguration
1608 + "C'. Supported are int and float values ending with C.",
1609 e);
1610 }
1611 } else {
1612 try {
1613 int threads = Integer.parseInt(threadConfiguration);
1614
1615 if (threads <= 0) {
1616 throw new IllegalArgumentException(
1617 "Invalid threads value: '" + threadConfiguration + "'. Value must be positive.");
1618 }
1619
1620 return threads;
1621 } catch (NumberFormatException e) {
1622 throw new IllegalArgumentException(
1623 "Invalid threads value: '" + threadConfiguration + "'. Supported are integer values.");
1624 }
1625 }
1626 }
1627
1628
1629 static void performProfileActivation(
1630 final CommandLine commandLine, final List<String> activeProfiles, final List<String> inactiveProfiles) {
1631 if (commandLine.hasOption(CLIManager.ACTIVATE_PROFILES)) {
1632 String[] profileOptionValues = commandLine.getOptionValues(CLIManager.ACTIVATE_PROFILES);
1633 if (profileOptionValues != null) {
1634 for (String profileOptionValue : profileOptionValues) {
1635 StringTokenizer profileTokens = new StringTokenizer(profileOptionValue, ",");
1636
1637 while (profileTokens.hasMoreTokens()) {
1638 String profileId = profileTokens.nextToken().trim();
1639 boolean active = true;
1640
1641 if (profileId.startsWith("-") || profileId.startsWith("!")) {
1642 active = false;
1643 profileId = profileId.substring(1);
1644 } else if (profileId.startsWith("+")) {
1645 profileId = profileId.substring(1);
1646 }
1647
1648
1649
1650 if (profileId.startsWith("?")) {
1651 profileId = profileId.substring(1);
1652 }
1653
1654 if (profileId.isEmpty()) {
1655 continue;
1656 }
1657
1658 if (active) {
1659 activeProfiles.add(profileId);
1660 } else {
1661 inactiveProfiles.add(profileId);
1662 }
1663 }
1664 }
1665 }
1666 }
1667 }
1668
1669
1670
1671
1672
1673 static void populateProperties(CliRequest cliRequest, Properties systemProperties, Properties userProperties)
1674 throws InterpolationException {
1675
1676
1677
1678
1679
1680
1681
1682 Properties cliProperties = new Properties();
1683 if (cliRequest.commandLine.hasOption(CLIManager.SET_USER_PROPERTY)) {
1684 String[] defStrs = cliRequest.commandLine.getOptionValues(CLIManager.SET_USER_PROPERTY);
1685
1686 if (defStrs != null) {
1687 String name;
1688 String value;
1689 for (String property : defStrs) {
1690 int i = property.indexOf('=');
1691 if (i <= 0) {
1692 name = property.trim();
1693 value = "true";
1694 } else {
1695 name = property.substring(0, i).trim();
1696 value = property.substring(i + 1);
1697 }
1698 cliProperties.setProperty(name, value);
1699 }
1700 }
1701 }
1702
1703 EnvironmentUtils.addEnvVars(systemProperties);
1704 SystemProperties.addSystemProperties(systemProperties);
1705
1706
1707 if (systemProperties.containsKey(MAVEN_REPO_CENTRAL_ENV)) {
1708 systemProperties.put(
1709 ModelInterpolator.MAVEN_REPO_CENTRAL_KEY, systemProperties.getProperty(MAVEN_REPO_CENTRAL_ENV));
1710 }
1711
1712 StringSearchInterpolator interpolator = createInterpolator(cliRequest, cliProperties, systemProperties);
1713 for (Map.Entry<Object, Object> e : cliProperties.entrySet()) {
1714 String name = (String) e.getKey();
1715 String value = interpolator.interpolate((String) e.getValue());
1716 userProperties.setProperty(name, value);
1717 }
1718
1719 systemProperties.putAll(userProperties);
1720
1721
1722
1723
1724
1725 userProperties.forEach((k, v) -> System.setProperty((String) k, (String) v));
1726
1727
1728
1729
1730
1731
1732 Properties buildProperties = CLIReportingUtils.getBuildProperties();
1733
1734 String mavenVersion = buildProperties.getProperty(CLIReportingUtils.BUILD_VERSION_PROPERTY);
1735 systemProperties.setProperty("maven.version", mavenVersion);
1736
1737 String mavenBuildVersion = CLIReportingUtils.createMavenVersionString(buildProperties);
1738 systemProperties.setProperty("maven.build.version", mavenBuildVersion);
1739 }
1740
1741 protected static StringSearchInterpolator createInterpolator(CliRequest cliRequest, Properties... properties) {
1742 StringSearchInterpolator interpolator = new StringSearchInterpolator();
1743 interpolator.addValueSource(new AbstractValueSource(false) {
1744 @Override
1745 public Object getValue(String expression) {
1746 if ("session.topDirectory".equals(expression)) {
1747 Path topDirectory = cliRequest.request.getTopDirectory();
1748 if (topDirectory != null) {
1749 return topDirectory.toString();
1750 } else {
1751 throw new IllegalUseOfUndefinedProperty(expression);
1752 }
1753 } else if ("session.rootDirectory".equals(expression)) {
1754 try {
1755 return cliRequest.request.getRootDirectory();
1756 } catch (IllegalStateException e) {
1757 throw new IllegalUseOfUndefinedProperty(expression);
1758 }
1759 }
1760 return null;
1761 }
1762 });
1763 interpolator.addValueSource(new AbstractValueSource(false) {
1764 @Override
1765 public Object getValue(String expression) {
1766 for (Properties props : properties) {
1767 Object val = props.getProperty(expression);
1768 if (val != null) {
1769 return val;
1770 }
1771 }
1772 return null;
1773 }
1774 });
1775 return interpolator;
1776 }
1777
1778 private static String stripLeadingAndTrailingQuotes(String str) {
1779 final int length = str.length();
1780 if (length > 1
1781 && str.startsWith("\"")
1782 && str.endsWith("\"")
1783 && str.substring(1, length - 1).indexOf('"') == -1) {
1784 str = str.substring(1, length - 1);
1785 }
1786
1787 return str;
1788 }
1789
1790 private static Path getCanonicalPath(Path path) {
1791 return path.toAbsolutePath().normalize();
1792 }
1793
1794 static class ExitException extends Exception {
1795 int exitCode;
1796
1797 ExitException(int exitCode) {
1798 this.exitCode = exitCode;
1799 }
1800 }
1801
1802 static class IllegalUseOfUndefinedProperty extends IllegalArgumentException {
1803 final String property;
1804
1805 IllegalUseOfUndefinedProperty(String property) {
1806 this.property = property;
1807 }
1808 }
1809
1810
1811
1812
1813
1814 protected TransferListener getConsoleTransferListener(boolean printResourceNames) {
1815 return new SimplexTransferListener(new ConsoleMavenTransferListener(System.out, printResourceNames));
1816 }
1817
1818 protected TransferListener getBatchTransferListener() {
1819 return new Slf4jMavenTransferListener();
1820 }
1821
1822 protected void customizeContainer(PlexusContainer container) {}
1823
1824 protected ModelProcessor createModelProcessor(PlexusContainer container) throws ComponentLookupException {
1825 return container.lookup(ModelProcessor.class);
1826 }
1827 }