forked from SceneGate/Yarhl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NodeFactory.cs
338 lines (292 loc) · 13.6 KB
/
NodeFactory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright (c) 2019 SceneGate
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace Yarhl.FileSystem
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Yarhl.IO;
/// <summary>
/// Node factory.
/// </summary>
public static class NodeFactory
{
/// <summary>
/// Creates a new <see cref="Node"/> with a new NodeContainer format.
/// </summary>
/// <returns>The new node.</returns>
/// <param name="name">Node name.</param>
[SuppressMessage(
"Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Ownserhip dispose transferred")]
public static Node CreateContainer(string name)
{
return new Node(name, new NodeContainerFormat());
}
/// <summary>
/// Creates the missing parent nodes to contain the child and add it.
/// </summary>
/// <param name="root">The root node that will contain the nodes.</param>
/// <param name="path">
/// The path for the child. It doesn't contain the root or child names.</param>
/// <param name="child">The child to add to root with the path.</param>
public static void CreateContainersForChild(Node root, string path, Node child)
{
if (root == null)
throw new ArgumentNullException(nameof(root));
if (child == null)
throw new ArgumentNullException(nameof(child));
if (path == null)
throw new ArgumentNullException(nameof(path));
// Replace wrong slashes to support native Windows paths
path = path.Replace("\\", NodeSystem.PathSeparator);
string[] parentNames = path.Split(
new[] { NodeSystem.PathSeparator[0] },
StringSplitOptions.RemoveEmptyEntries);
Node currentNode = root;
foreach (string name in parentNames) {
Node subParent = currentNode.Children[name];
if (subParent == null) {
subParent = CreateContainer(name);
currentNode.Add(subParent);
}
currentNode = subParent;
}
currentNode.Add(child);
}
/// <summary>
/// Creates a Node with a new stream from memory.
/// </summary>
/// <param name="name">The name of the node.</param>
/// <returns>The new node.</returns>
[SuppressMessage(
"Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Ownserhip dispose transferred")]
public static Node FromMemory(string name)
{
return new Node(name, new BinaryFormat());
}
/// <summary>
/// Creates a Node from a part of a stream.
/// </summary>
/// <param name="name">The name of the node.</param>
/// <param name="source">The source / parent stream.</param>
/// <param name="offset">
/// The offset in the source stream where the node starts.
/// </param>
/// <param name="length">The length of the data in the node.</param>
/// <remarks>
/// <para>This format creates an internal <see cref="DataStream" /> from the
/// provided stream. It will take over the ownership of the stream
/// argument, you should not dispose this argument, unless you are
/// providing a <see cref="DataStream" /> in which case it is safe and
/// recommended to dispose it.</para>
/// </remarks>
/// <returns>The new node.</returns>
[SuppressMessage(
"Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Ownserhip dispose transferred")]
public static Node FromSubstream(
string name,
Stream source,
long offset,
long length)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
var binary = new BinaryFormat(source, offset, length);
return new Node(name, binary);
}
/// <summary>
/// Creates a Node from a file.
/// </summary>
/// <returns>The node.</returns>
/// <param name="filePath">File path.</param>
/// <param name="mode">The mode to open the file.</param>
public static Node FromFile(string filePath, FileOpenMode mode = FileOpenMode.ReadWrite)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));
string filename = Path.GetFileName(filePath);
return FromFile(filePath, filename, mode);
}
/// <summary>
/// Creates a Node from a file.
/// </summary>
/// <returns>The node.</returns>
/// <param name="filePath">File path.</param>
/// <param name="nodeName">Node name.</param>
/// <param name="mode">The mode to open the file.</param>
[SuppressMessage(
"Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Ownserhip dispose transferred")]
public static Node FromFile(string filePath, string nodeName, FileOpenMode mode = FileOpenMode.ReadWrite)
{
// We need to catch if the node creation fails
// for instance for null names, to dispose the stream.
var format = new BinaryFormat(DataStreamFactory.FromFile(filePath, mode));
Node node;
try {
node = new Node(nodeName, format) {
Tags = { ["FileInfo"] = new FileInfo(filePath) },
};
} catch {
format.Dispose();
throw;
}
return node;
}
/// <summary>
/// Creates a Node containing all the files from the directory.
/// </summary>
/// <returns>The container node.</returns>
/// <param name="dirPath">Directory path.</param>
/// <param name="filter">Filter for files in directory.</param>
/// <param name="mode">The mode to open the files.</param>
public static Node FromDirectory(string dirPath, string filter = "*", FileOpenMode mode = FileOpenMode.ReadWrite)
{
if (string.IsNullOrEmpty(dirPath))
throw new ArgumentNullException(nameof(dirPath));
// This sanitizes the path and remove double slashes
dirPath = Path.GetFullPath(dirPath);
if (dirPath[dirPath.Length - 1] == Path.DirectorySeparatorChar) {
dirPath = dirPath.Remove(dirPath.Length - 1);
}
string dirName = Path.GetFileName(dirPath);
return FromDirectory(dirPath, filter, dirName, false, mode);
}
/// <summary>
/// Creates a Node containing all the files from the directory.
/// </summary>
/// <returns>The container node.</returns>
/// <param name="dirPath">Directory path.</param>
/// <param name="filter">Filter for files in directory.</param>
/// <param name="nodeName">Node name.</param>
/// <param name="subDirectories">
/// If <see langword="true" /> it searchs recursively in subdirectories.
/// </param>
/// <param name="mode">The mode to open the files.</param>
[SuppressMessage(
"Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Ownserhip dispose transferred")]
public static Node FromDirectory(
string dirPath,
string filter,
string nodeName,
bool subDirectories = false,
FileOpenMode mode = FileOpenMode.ReadWrite)
{
if (string.IsNullOrEmpty(dirPath))
throw new ArgumentNullException(nameof(dirPath));
if (string.IsNullOrEmpty(filter))
throw new ArgumentNullException(nameof(filter));
if (string.IsNullOrEmpty(nodeName))
throw new ArgumentNullException(nameof(nodeName));
SearchOption options = subDirectories ?
SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
// This sanitizes the path and remove double slashes
dirPath = Path.GetFullPath(dirPath);
string[] fileList = Directory.GetFiles(dirPath, filter, options);
return FromFileList(dirPath, nodeName, fileList, mode);
}
/// <summary>
/// Creates a Node containing all the files from the directory.
/// </summary>
/// <returns>The container node.</returns>
/// <param name="dirPath">Directory path.</param>
/// <param name="filter">Filter for files in directory.</param>
/// <param name="mode">The mode to open the files.</param>
public static Node FromDirectory(string dirPath, Func<string, bool> filter, FileOpenMode mode = FileOpenMode.ReadWrite)
{
if (string.IsNullOrEmpty(dirPath))
throw new ArgumentNullException(nameof(dirPath));
if (filter == null)
throw new ArgumentNullException(nameof(filter));
// This sanitizes the path and remove double slashes
dirPath = Path.GetFullPath(dirPath);
if (dirPath[dirPath.Length - 1] == Path.DirectorySeparatorChar) {
dirPath = dirPath.Remove(dirPath.Length - 1);
}
string dirName = Path.GetFileName(dirPath);
return FromDirectory(dirPath, filter, dirName, false, mode);
}
/// <summary>
/// Creates a Node containing all the files from the directory.
/// </summary>
/// <returns>The container node.</returns>
/// <param name="dirPath">Directory path.</param>
/// <param name="filter">Filter for files in directory.</param>
/// <param name="nodeName">Node name.</param>
/// <param name="subDirectories">
/// If <see langword="true" /> it searchs recursively in subdirectories.
/// </param>
/// <param name="mode">The mode to open the files.</param>
[SuppressMessage(
"Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Ownserhip dispose transferred")]
public static Node FromDirectory(
string dirPath,
Func<string, bool> filter,
string nodeName,
bool subDirectories = false,
FileOpenMode mode = FileOpenMode.ReadWrite)
{
if (string.IsNullOrEmpty(dirPath))
throw new ArgumentNullException(nameof(dirPath));
if (filter == null)
throw new ArgumentNullException(nameof(filter));
if (string.IsNullOrEmpty(nodeName))
throw new ArgumentNullException(nameof(nodeName));
SearchOption options = subDirectories ?
SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
// This sanitizes the path and remove double slashes
dirPath = Path.GetFullPath(dirPath);
if (dirPath[dirPath.Length - 1] == Path.DirectorySeparatorChar) {
dirPath = dirPath.Remove(dirPath.Length - 1);
}
string[] allFiles = Directory.GetFiles(dirPath, "*", options);
string[] fileList = Array.FindAll(allFiles, x => filter(x));
return FromFileList(dirPath, nodeName, fileList, mode);
}
private static Node FromFileList(string dirPath, string nodeName, IEnumerable<string> fileList, FileOpenMode mode = FileOpenMode.ReadWrite)
{
Node folder = CreateContainer(nodeName);
folder.Tags["DirectoryInfo"] = new DirectoryInfo(dirPath);
foreach (string filePath in fileList) {
string relParent = Path.GetDirectoryName(filePath)
.Replace(dirPath, string.Empty);
CreateContainersForChild(folder, relParent, FromFile(filePath, mode));
}
foreach (Node node in Navigator.IterateNodes(folder)) {
if (!node.IsContainer || node.Tags.ContainsKey("DirectoryInfo")) {
continue;
}
int rootPathLength = $"{NodeSystem.PathSeparator}{nodeName}".Length;
string nodePath = Path.GetFullPath(string.Concat(dirPath, node.Path.Substring(rootPathLength)));
node.Tags["DirectoryInfo"] = new DirectoryInfo(nodePath);
}
return folder;
}
}
}