1 package eu.simuline.m2latex.core;
2
3 import java.io.File;
4
5 import java.util.Collection;
6 import java.util.Set;
7 import java.util.TreeSet;
8 import java.util.Map;
9 import java.util.TreeMap;
10
11 /**
12 * Represents the contents of a directory.
13 *
14 *
15 * Created: Tue Dec 6 03:05:24 2016
16 *
17 * @author <a href="mailto:rei3ner@arcor.de">Ernst Reissner</a>
18 * @version 1.0
19 */
20 public class DirNode {
21
22 // null iff this DirNode is invalid according to isValid()
23 /**
24 * The set of names of regular files, i.e. files except directories
25 * in the directory described by this node.
26 * If the directory described by this node is not readable,
27 * this field is <code>null</code>.
28 *
29 * @see #isValid()
30 */
31 private final Set<String> regularFileNames;
32
33 /**
34 * The set of subdirectories
35 * in the directory described by this node:
36 * The keys are the names and the according values
37 * are the nodes describing the subdirectories.
38 * If the directory described by this node is not readable,
39 * this field is <code>null</code>.
40 *
41 * @see #isValid()
42 */
43 private final Map<String, DirNode> name2node;
44
45 /**
46 * Creates a new <code>DirNode</code> instance.
47 * <p>
48 * Logging:
49 * WFU01: Cannot read directory
50 *
51 * @param dir
52 * The directory this node represents
53 * including subdirectories recursively.
54 * This is the latex source directory or a subdirectory recursively.
55 * @param fileUtils
56 *
57 */
58 // used recursively but in addition only in
59 // TexFileUtils.cleanUpRec,
60 // LatexProcessor.create()
61 // LatexProcessor.processGraphics()
62 // LatexProcessor.clearAll()
63 public DirNode(File dir, TexFileUtils fileUtils) {
64 assert dir.isDirectory() : "The file '" + dir + "' is no directory. ";
65 // may log WFU01 Cannot read directory
66 File[] files = fileUtils.listFilesOrWarn(dir);
67 if (files == null) {
68 // Here, this node is irregular
69 this.regularFileNames = null;
70 this.name2node = null;
71 return;
72 }
73 this.regularFileNames = new TreeSet<String>();
74 this.name2node = new TreeMap<String, DirNode>();
75 DirNode node;
76 for (File file : files) {
77 assert file.exists() : "The file '" + file + "' does not exist. ";
78 if (file.isDirectory()) {
79 // may log WFU01 Cannot read directory
80 node = new DirNode(file, fileUtils);
81 if (node.isValid()) {
82 this.name2node.put(file.getName(), node);
83 }
84 } else {
85 // FIXME: skip hidden files
86 this.regularFileNames.add(file.getName());
87 }
88 }
89 }
90
91 /**
92 * Whether the directory described by this node is readable.
93 */
94 boolean isValid() {
95 assert (this.regularFileNames == null) == (this.name2node == null);
96 return this.regularFileNames != null;
97 }
98
99 Set<String> getRegularFileNames() {
100 return this.regularFileNames;
101 }
102
103 Map<String, DirNode> getSubdirs() {
104 return this.name2node;
105 }
106 }