2 * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.checkstyle;
11 import java.nio.file.Path;
12 import java.util.Optional;
15 * Utility to convert absolute file name to path relative to project.
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.
20 * @see <a href="https://groups.google.com/forum/#!topic/checkstyle-devel/Rfwx81YhVQk">checkstyle-devel list thread</a>
22 public class FileNameUtil {
24 private FileNameUtil() {
27 static File getPathRelativeToMavenProjectRootIfPossible(File absoluteFile) {
28 return getOptionalPathRelativeToMavenProjectRoot(absoluteFile).orElse(absoluteFile);
31 static Optional<File> getOptionalPathRelativeToMavenProjectRoot(File absoluteFile) {
32 if (!absoluteFile.isAbsolute()) {
33 return Optional.of(absoluteFile);
35 File projectRoot = absoluteFile;
36 while (!isProjectRootDir(projectRoot) && projectRoot.getParentFile() != null) {
37 projectRoot = projectRoot.getParentFile();
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());
45 return Optional.empty();
48 private static boolean isProjectRootDir(File file) {
49 return new File(file, "pom.xml").exists();