New LogMessageExtractorCheck which writes out TXT report of all loggers
[yangtools.git] / common / checkstyle-logging / src / main / java / org / opendaylight / yangtools / checkstyle / FileNameUtil.java
1 /*
2  * Copyright (c) 2016 Red Hat, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.checkstyle;
9
10 import java.io.File;
11 import java.nio.file.Path;
12 import java.util.Optional;
13
14 /**
15  * Utility to convert absolute file name to path relative to project.
16  *
17  * <p>Current implementation use a sad heuristic based on detecting a pom.xml.
18  * This is of course sub-optimal to say the very least.  Improvements welcome.
19  *
20  * @see <a href="https://groups.google.com/forum/#!topic/checkstyle-devel/Rfwx81YhVQk">checkstyle-devel list thread</a>
21  */
22 public class FileNameUtil {
23
24     private FileNameUtil() {
25     }
26
27     static File getPathRelativeToMavenProjectRootIfPossible(File absoluteFile) {
28         return getOptionalPathRelativeToMavenProjectRoot(absoluteFile).orElse(absoluteFile);
29     }
30
31     static Optional<File> getOptionalPathRelativeToMavenProjectRoot(File absoluteFile) {
32         if (!absoluteFile.isAbsolute()) {
33             return Optional.of(absoluteFile);
34         }
35         File projectRoot = absoluteFile;
36         while (!isProjectRootDir(projectRoot) && projectRoot.getParentFile() != null) {
37             projectRoot = projectRoot.getParentFile();
38         }
39         if (isProjectRootDir(projectRoot)) {
40             Path absolutePath = absoluteFile.toPath();
41             Path basePath = projectRoot.toPath();
42             Path relativePath = basePath.relativize(absolutePath);
43             return Optional.of(relativePath.toFile());
44         }
45         return Optional.empty();
46     }
47
48     private static boolean isProjectRootDir(File file) {
49         return new File(file, "pom.xml").exists();
50     }
51
52 }