001/* 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.mybatisflex.processor.util; 018 019import java.io.File; 020import java.util.Arrays; 021import java.util.HashSet; 022import java.util.Set; 023 024/** 025 * 文件工具类。 026 * 027 * @author 王帅 028 * @since 2023-06-22 029 */ 030public class FileUtil { 031 032 private FileUtil() { 033 } 034 035 private static Set<String> flagFileNames = new HashSet<>(Arrays.asList("pom.xml", "build.gradle", "build.gradle.kts")); 036 037 038 public static boolean existsBuildFile(File dir) { 039 for (String fileName : flagFileNames) { 040 if (new File(dir, fileName).exists()) { 041 return true; 042 } 043 } 044 return false; 045 } 046 047 public static boolean isFromTestSource(String path) { 048 return path.contains("test-sources") || path.contains("test-annotations"); 049 } 050 051 public static boolean isAbsolutePath(String path) { 052 return path != null && (path.startsWith("/") || path.contains(":")); 053 } 054 055 /** 056 * 获取项目的根目录,也就是根节点 pom.xml 所在的目录 057 */ 058 public static String getProjectRootPath(String genFilePath) { 059 File file = new File(genFilePath); 060 int count = 20; 061 return getProjectRootPath(file, count); 062 } 063 064 public static String getProjectRootPath(File file, int depth) { 065 if (depth <= 0) { 066 return null; 067 } 068 if (file.isFile()) { 069 return getProjectRootPath(file.getParentFile(), depth - 1); 070 } else { 071 if (existsBuildFile(file) && !existsBuildFile(file.getParentFile())) { 072 return file.getAbsolutePath(); 073 } else { 074 return getProjectRootPath(file.getParentFile(), depth - 1); 075 } 076 } 077 } 078 079}