1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.model.root;
20
21 import javax.inject.Named;
22
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.util.Optional;
28
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 @Named
33 public class DefaultRootLocator implements RootLocator {
34 private final Logger logger = LoggerFactory.getLogger(getClass());
35
36 @Override
37 public Path findRoot(Path basedir) {
38 Path rootDirectory = basedir;
39 while (rootDirectory != null && !isRootDirectory(rootDirectory)) {
40 rootDirectory = rootDirectory.getParent();
41 }
42 return rootDirectory;
43 }
44
45 @Override
46 public Path findMandatoryRoot(Path basedir) {
47 Path rootDirectory = findRoot(basedir);
48 Optional<Path> rdf = getRootDirectoryFallback();
49 if (rootDirectory == null) {
50 rootDirectory = rdf.orElseThrow(() -> new IllegalStateException(getNoRootMessage()));
51 } else {
52 if (rdf.isPresent()) {
53 try {
54 if (!Files.isSameFile(rootDirectory, rdf.get())) {
55 logger.warn("Project root directory and multiModuleProjectDirectory are not aligned");
56 }
57 } catch (IOException e) {
58 throw new IllegalStateException("findMandatoryRoot failed", e);
59 }
60 }
61 }
62 return rootDirectory;
63 }
64
65 protected Optional<Path> getRootDirectoryFallback() {
66 String mmpd = System.getProperty("maven.multiModuleProjectDirectory");
67 if (mmpd != null) {
68 return Optional.of(getCanonicalPath(Paths.get(mmpd)));
69 }
70 return Optional.empty();
71 }
72
73 protected Path getCanonicalPath(Path path) {
74 return path.toAbsolutePath().normalize();
75 }
76
77 public boolean isRootDirectory(Path dir) {
78 return Files.isDirectory(dir.resolve(".mvn"));
79 }
80 }