Просмотр исходного кода

Refactor submission set building.

Alberth 5 лет назад
Родитель
Сommit
e5274c7f52

+ 1 - 46
jplag/src/main/java/de/jplag/JPlag.java

@@ -1,12 +1,9 @@
 package de.jplag;
 
-import java.io.File;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 
-import de.jplag.exceptions.BasecodeException;
 import de.jplag.exceptions.ExitException;
-import de.jplag.exceptions.RootDirectoryException;
 import de.jplag.exceptions.SubmissionException;
 import de.jplag.options.JPlagOptions;
 import de.jplag.options.LanguageOption;
@@ -38,7 +35,6 @@ public class JPlag {
         coreAlgorithm = new GreedyStringTiling(options);
         initializeLanguage();
         initializeComparisonStrategy();
-        checkBaseCodeOption();
     }
 
     /**
@@ -49,7 +45,7 @@ public class JPlag {
     public JPlagResult run() throws ExitException {
         // Parse and validate submissions.
         SubmissionSetBuilder builder = new SubmissionSetBuilder(language, options, errorCollector);
-        SubmissionSet submissionSet = builder.buildSubmissionSet(getRootDirectory());
+        SubmissionSet submissionSet = builder.buildSubmissionSet();
 
         if (submissionSet.hasBaseCode()) {
             coreAlgorithm.createHashes(submissionSet.getBaseCode().getTokenList(), options.getMinimumTokenMatch(), true);
@@ -66,47 +62,6 @@ public class JPlag {
         return result;
     }
 
-    /**
-     * This method checks whether the base code directory value is valid.
-     */
-    private void checkBaseCodeOption() throws ExitException {
-        getRootDirectory(); // Performs checks on the root directory.
-
-        if (options.hasBaseCode()) {
-            String baseCode = options.getBaseCodeSubmissionName();
-            if (baseCode.contains(".")) {
-                throw new BasecodeException("The basecode directory name \"" + baseCode + "\" cannot contain dots!");
-            }
-            String baseCodePath = options.getRootDirectoryName() + File.separator + baseCode;
-            if (!new File(baseCodePath).exists()) {
-                throw new BasecodeException("Basecode directory \"" + baseCodePath + "\" doesn't exist!");
-            }
-
-            String subdirectory = options.getSubdirectoryName();
-            if (subdirectory != null && subdirectory.length() != 0) {
-                if (!new File(baseCodePath, subdirectory).exists()) {
-                    throw new BasecodeException("Basecode directory doesn't contain" + " the subdirectory \"" + subdirectory + "\"!");
-                }
-            }
-            System.out.println("Basecode directory \"" + baseCodePath + "\" will be used");
-        }
-    }
-
-    /**
-     * Check sanity of the root directory name in the options, and construct file system access to it.
-     */
-    private File getRootDirectory() throws ExitException {
-        String rootDirectoryName = options.getRootDirectoryName();
-        File rootDir = new File(rootDirectoryName);
-        if (!rootDir.exists()) {
-            throw new RootDirectoryException(String.format("Root directory \"%s\" does not exist!", rootDirectoryName));
-        }
-        if (!rootDir.isDirectory()) {
-            throw new RootDirectoryException(String.format("Root directory \"%s\" is not a directory!", rootDirectoryName));
-        }
-        return rootDir;
-    }
-
     private void initializeComparisonStrategy() {
         switch (options.getComparisonMode()) {
         case NORMAL:

+ 1 - 1
jplag/src/main/java/de/jplag/Submission.java

@@ -31,7 +31,7 @@ public class Submission implements Comparable<Submission> {
     private final String name;
 
     /**
-     * Root of the submission (either a file or a directory).
+     * Root of the submission files (including the subdir if used).
      */
     private final File submissionRoot;
 

+ 95 - 35
jplag/src/main/java/de/jplag/SubmissionSetBuilder.java

@@ -11,9 +11,12 @@ import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.Optional;
 
+import de.jplag.exceptions.BasecodeException;
 import de.jplag.exceptions.ExitException;
 import de.jplag.exceptions.RootDirectoryException;
 import de.jplag.exceptions.SubmissionException;
@@ -45,54 +48,95 @@ public class SubmissionSetBuilder {
 
     /**
      * Builds a submission set for all submissions of a specific directory.
-     * @param rootDirectory is the specific directory.
      * @return the newly built submission set.
      * @throws ExitException if the directory cannot be read.
      */
-    public SubmissionSet buildSubmissionSet(File rootDirectory) throws ExitException {
-        String[] fileNames;
+    public SubmissionSet buildSubmissionSet() throws ExitException {
+        // Read the root directory and collect valid looking submission entries from it.
+        File rootDirectory = new File(options.getRootDirectoryName());
+        verifyRootdirExistence(rootDirectory);
+        String[] fileNames = readSubmissionRootNames(rootDirectory);
+        Map<String, Submission> foundSubmissions = processRootDirEntries(rootDirectory, fileNames);
+
+        // Extract the basecode submission if necessary.
+        Optional<Submission> baseCodeSubmission = Optional.empty();
+        if (options.hasBaseCode()) {
+            verifyBaseCodeName();
 
-        try {
-            fileNames = rootDirectory.list();
-        } catch (SecurityException exception) {
-            throw new RootDirectoryException("Cannot list files of the root directory! " + exception.getMessage());
-        }
+            String baseCodeName = options.getBaseCodeSubmissionName();
+            String baseCodePath = rootDirectory.toString() + File.separator + baseCodeName;
 
-        if (fileNames == null) {
-            throw new RootDirectoryException(
-                    "Cannot list files of the root directory! Make sure the specified root directory is in fact a directory.");
-        }
+            // Grab the basecode submission and erase it from the regular submissions.
+            Submission foundBaseCodeSubmission = foundSubmissions.get(baseCodeName);
+            if (foundBaseCodeSubmission == null) {
+                throw new BasecodeException("Basecode submission \"" + baseCodePath + "\" doesn't exist!");
+            }
 
-        Arrays.sort(fileNames);
+            foundSubmissions.remove(baseCodeName);
+            baseCodeSubmission = Optional.of(foundBaseCodeSubmission);
+            System.out.println("Basecode directory \"" + baseCodePath + "\" will be used");
+        }
 
-        return mapFileNamesToSubmissions(fileNames, rootDirectory);
+        // Merge everything in a submission set.
+        List<Submission> submissions = new ArrayList<>(foundSubmissions.values());
+        return new SubmissionSet(submissions, baseCodeSubmission, errorCollector, options);
     }
 
     /**
-     * Checks if a file has a valid suffix for the current language.
-     * @param file is the file to check.
-     * @return true if the file suffix matches the language.
+     * Verify that the given root directory exists.
      */
-    private boolean hasValidSuffix(File file) {
-        String[] validSuffixes = options.getFileSuffixes();
+    private void verifyRootdirExistence(File rootDir) throws ExitException {
+        String rootDirectoryName = rootDir.getName();
+        if (!rootDir.exists()) {
+            throw new RootDirectoryException(String.format("Root directory \"%s\" does not exist!", rootDirectoryName));
+        }
+        if (!rootDir.isDirectory()) {
+            throw new RootDirectoryException(String.format("Root directory \"%s\" is not a directory!", rootDirectoryName));
+        }
+    }
 
-        // This is the case if either the language frontends or the CLI did not set the valid suffixes array in options
-        if (validSuffixes == null || validSuffixes.length == 0) {
-            return true;
+    /**
+     * Verify the basecode name.
+     */
+    private void verifyBaseCodeName() throws ExitException {
+        String name = options.getBaseCodeSubmissionName();
+        if (name.contains(".")) {
+            throw new BasecodeException("The basecode directory name \"" + name + "\" cannot contain dots!");
         }
-        return Arrays.stream(validSuffixes).anyMatch(suffix -> file.getName().endsWith(suffix));
     }
 
     /**
-     * Checks if a file is excluded or not.
+     * Read entries in the given root directory.
      */
-    private boolean isFileExcluded(File file) {
-        return excludedFileNames.stream().anyMatch(excludedName -> file.getName().endsWith(excludedName));
+    private String[] readSubmissionRootNames(File rootDirectory) throws ExitException {
+        if (!rootDirectory.isDirectory()) {
+            throw new AssertionError("Given root is not a directory.");
+        }
+
+        String[] fileNames;
+
+        try {
+            fileNames = rootDirectory.list();
+        } catch (SecurityException exception) {
+            throw new RootDirectoryException("Cannot list files of the root directory! " + exception.getMessage());
+        }
+
+        if (fileNames == null) {
+            throw new RootDirectoryException("Cannot list files of the root directory!");
+        }
+
+        Arrays.sort(fileNames);
+        return fileNames;
     }
 
-    private SubmissionSet mapFileNamesToSubmissions(String[] fileNames, File rootDirectory) throws ExitException {
-        List<Submission> submissions = new ArrayList<>();
-        Optional<Submission> baseCodeSubmission = Optional.empty();
+    /**
+     * Process entries in the root directory to check whether they qualify as submissions.
+     * @param rootDirectory Root directory being examined.
+     * @param fileNames Entries found in the root directory.
+     * @return Candidate submissions ordered by their name.
+     */
+    private Map<String, Submission> processRootDirEntries(File rootDirectory, String[] fileNames) throws ExitException {
+        Map<String, Submission> foundSubmissions = new LinkedHashMap<>(fileNames.length); // Capacity is an over-estimate.
 
         for (String fileName : fileNames) {
             File submissionFile = new File(rootDirectory, fileName);
@@ -122,15 +166,31 @@ public class SubmissionSetBuilder {
             }
 
             Submission submission = new Submission(fileName, submissionFile, parseFilesRecursively(submissionFile), language, errorCollector);
+            foundSubmissions.put(fileName, submission);
+        }
+        return foundSubmissions;
+    }
 
-            if (options.hasBaseCode() && options.getBaseCodeSubmissionName().equals(fileName)) {
-                baseCodeSubmission = Optional.of(submission);
-            } else {
-                submissions.add(submission);
-            }
+    /**
+     * Checks if a file has a valid suffix for the current language.
+     * @param file is the file to check.
+     * @return true if the file suffix matches the language.
+     */
+    private boolean hasValidSuffix(File file) {
+        String[] validSuffixes = options.getFileSuffixes();
+
+        // This is the case if either the language frontends or the CLI did not set the valid suffixes array in options
+        if (validSuffixes == null || validSuffixes.length == 0) {
+            return true;
         }
+        return Arrays.stream(validSuffixes).anyMatch(suffix -> file.getName().endsWith(suffix));
+    }
 
-        return new SubmissionSet(submissions, baseCodeSubmission, errorCollector, options);
+    /**
+     * Checks if a file is excluded or not.
+     */
+    private boolean isFileExcluded(File file) {
+        return excludedFileNames.stream().anyMatch(excludedName -> file.getName().endsWith(excludedName));
     }
 
     /**