This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/Nitride.IO/Contents/ReadFiles.cs
Dylan R. E. Moonfire 78054ee2a7 feat: initial release
2021-09-07 00:15:45 -05:00

90 lines
3 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Linq;
using DotNet.Globbing;
using Gallium;
using Nitride.Contents;
using Zio;
namespace Nitride.IO.Contents
{
/// <summary>
/// A module that reads files from the file system and wraps them in an
/// entity with the following components: UPath, IContent.
/// </summary>
public class ReadFiles : FileSystemOperation
{
public ReadFiles(IFileSystem fileSystem)
: base(fileSystem)
{
}
/// <summary>
/// Primary method for creating a read file.
/// </summary>
public delegate ReadFiles Factory(IFileSystem fileSystem);
/// <summary>
/// Reads all files from the file system and returns them.
/// </summary>
/// <returns>A populated collection of entities.</returns>
public IEnumerable<Entity> Read(
UPath path = new(),
string searchPattern = "*",
SearchOption search = SearchOption.AllDirectories)
{
// Normalize the path.
path = path == new UPath() ? "/" : path;
// Search for the file and wrap the results.
IEnumerable<FileEntry> files = this.FileSystem
.EnumerateFileEntries(path, searchPattern, search);
IEnumerable<Entity> entities = files.Select(this.ToEntity);
return entities;
}
/// <summary>
/// Reads all files from the file system and returns them.
/// </summary>
/// <returns>A populated collection of entities.</returns>
public IEnumerable<Entity> Read(string glob)
{
Glob parsed = Glob.Parse(glob);
return this.Read(parsed);
}
/// <summary>
/// Reads all files from the file system, filtering them out by the
/// minimatch pattern (as defined by DotNet.Blob).
/// </summary>
/// <returns>A populated collection of entities.</returns>
public IEnumerable<Entity> Read(Glob glob)
{
IEnumerable<FileEntry> files = this.FileSystem
.EnumerateFileEntries("/", "*.*", SearchOption.AllDirectories)
.Where(x => glob.IsMatch(x.Path.ToString()));
IEnumerable<Entity> entities = files.Select(this.ToEntity);
return entities;
}
/// <summary>
/// Creates an entity with the standard components for all Zio-based
/// files. This attaches the file's path relative to the file system
/// and a way of accessing the content from the file system.
/// </summary>
/// <param name="file">The Zio file entry.</param>
/// <returns>An Entity with appropriate content.</returns>
private Entity ToEntity(FileEntry file)
{
Entity entity = new Entity()
.Set(file.Path)
.SetBinaryContent(new FileEntryBinaryContent(file));
return entity;
}
}
}