使用.gitignore的内容与Java NIO PathMatcher进行相同的过滤

时间:2019-07-14 21:53:07

标签: git filter nio

我正在使用FileSystem#getPathMatcher(glob-syntax).matches(...)在复制过程中过滤掉文件。

我想要与git相同的过滤行为。因此,我想重用.gitignore文件中的glob-definitions。

到目前为止,我还没有设法对git进行相同的过滤。

public class GitignorePathMatcher {


    public static void main(String[] args) throws IOException {
        Path start = Paths.get("/home/carsten/project");
        List<String> lines = Files.readAllLines(start.resolve(".gitignore"));
        for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext();) {
            String line = iterator.next();
            String trim = line.trim();
            if (trim.length() == 0 || trim.contains("#")) iterator.remove();
            else iterator.set(trim);
        }

        print(lines);
        System.out.println();

        filter(lines, start);
    }

    private static void filter(List<String> filters, Path start) throws IOException {
        FileSystem fs = start.getFileSystem();

        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                boolean include = include(dir, filters);
                System.out.println((include ? "ADD " : "[SKIP] ") + dir);
                return include ? CONTINUE : SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                boolean include = include(file, filters);
                System.out.println((include ? "ADD \t" : "[SKIP] \t") + file);
                return CONTINUE;
            }

            boolean include(Path dir, List<String> filters) {
                for (String pattern : filters) {
                    if (fs.getPathMatcher("glob:" + pattern).matches(dir)) return false;
                }
                return true;
            }
        });
    }


    private static void print(List<String> lines) {
        for (String line : lines) System.out.println(line);
    }

}

0 个答案:

没有答案