From 50730c7784ee742c8c148d4d5b07c4ea312a8e58 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 12 Jan 2025 17:29:05 +0000 Subject: Improve collection of source files --- .../java/org/shedlang/compiler/SourceFiles.java | 78 ++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/main/java/org/shedlang/compiler/SourceFiles.java (limited to 'src/main/java/org/shedlang/compiler/SourceFiles.java') diff --git a/src/main/java/org/shedlang/compiler/SourceFiles.java b/src/main/java/org/shedlang/compiler/SourceFiles.java new file mode 100644 index 00000000..451c52fa --- /dev/null +++ b/src/main/java/org/shedlang/compiler/SourceFiles.java @@ -0,0 +1,78 @@ +package org.shedlang.compiler; + +import org.shedlang.compiler.types.NamespaceName; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; + +public class SourceFiles { + private SourceFiles() { + } + + public static List collectSourceFiles( + Path sourceRoot + ) throws IOException { + var sourceFiles = new ArrayList(); + + Files.walkFileTree(sourceRoot, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile( + Path file, + BasicFileAttributes attrs + ) { + var namespaceName = relativeSourcePathToNamespaceName( + sourceRoot.relativize(file) + ); + if (namespaceName.isPresent()) { + var sourceFile = new SourceFile(file, namespaceName.get()); + sourceFiles.add(sourceFile); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory( + Path dir, + IOException exc + ) { + return FileVisitResult.CONTINUE; + } + }); + sourceFiles.sort(Comparator.comparing(x -> x.path(), Comparator.naturalOrder())); + return sourceFiles; + } + + private static Optional relativeSourcePathToNamespaceName( + Path relativeSourcePath + ) { + var fileName = relativeSourcePath.getFileName().toString(); + var shedSuffix = ".shed"; + if (!fileName.endsWith(shedSuffix)) { + return Optional.empty(); + } + var namespaceNameParts = new ArrayList(); + + for (var i = 0; i < relativeSourcePath.getNameCount() - 1; i++) { + namespaceNameParts.add(relativeSourcePath.getName(i).toString()); + } + + namespaceNameParts.add(fileName.substring(0, fileName.length() - shedSuffix.length())); + + for (var part : namespaceNameParts) { + if (part.contains(".")) { + // TODO: parse namespace part + return Optional.empty(); + } + } + + return Optional.of(new NamespaceName(namespaceNameParts)); + } +} -- cgit v1.2.3