001package gudusoft.gsqlparser.util;
002
003import gudusoft.gsqlparser.dlineage.util.ProcessUtility;
004
005import java.io.File;
006import java.io.IOException;
007import java.nio.file.*;
008import java.util.ArrayList;
009import java.util.List;
010
011public class FileUtil {
012
013    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
014
015    public static List<File> resolveInputFiles(String inputPath) {
016        List<File> result = new ArrayList<>();
017        File input = new File(inputPath);
018        // 判断是否是 glob 模式
019        if (containsGlobPattern(inputPath)) {
020            // 使用 FileSystem 的 PathMatcher 处理 glob
021            PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + inputPath);
022            Path root = findSearchRoot(inputPath);
023
024            try {
025                Files.walk(root)
026                        .filter(Files::isRegularFile)
027                        .filter(p -> matcher.matches(p))
028                        .forEach(p -> result.add(p.toFile()));
029            } catch (IOException e) {
030                logger.error("Error reading files", e);
031            }
032        } else if (input.isDirectory()) {
033            // 是目录,递归收集 .sql 文件
034            try {
035                Files.walk(input.toPath())
036                        .filter(Files::isRegularFile)
037                        .filter(p -> p.toString().toLowerCase().endsWith(".sql"))
038                        .forEach(p -> result.add(p.toFile()));
039            } catch (IOException e) {
040                logger.error("Error reading directory", e);
041            }
042        } else if (input.isFile()) {
043            // 是普通文件
044            result.add(input);
045        }
046
047        return result;
048    }
049
050    private static boolean containsGlobPattern(String path) {
051        return path.contains("*") || path.contains("?") || path.contains("[") || path.contains("{");
052    }
053
054    private static Path findSearchRoot(String globPattern) {
055        // 去除 glob 部分,找出能作为起始目录的部分
056        int wildcardIndex = globPattern.indexOf('*');
057        if (wildcardIndex == -1) wildcardIndex = globPattern.indexOf('?');
058        if (wildcardIndex == -1) wildcardIndex = globPattern.length();
059        String root = globPattern.substring(0, wildcardIndex);
060        File rootFile = new File(root);
061        while (!rootFile.exists() || !rootFile.isDirectory()) {
062            rootFile = rootFile.getParentFile();
063            if (rootFile == null) {
064                return Paths.get(".").toAbsolutePath().normalize(); // fallback
065            }
066        }
067        return rootFile.toPath();
068    }
069}