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/MfGames.Nitride.IO/Contents/ReadFiles.cs

92 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DotNet.Globbing;
using FluentValidation;
using MfGames.Gallium;
using MfGames.Nitride.Contents;
using Zio;
namespace MfGames.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>
[WithProperties]
public partial class ReadFiles : FileSystemOperationBase
{
private readonly IValidator<ReadFiles> validator;
public ReadFiles(
IValidator<ReadFiles> validator,
IFileSystem fileSystem)
: base(fileSystem)
{
this.validator = validator;
}
/// <summary>
/// Gets or sets the file pattern to retrieve fields. This supports
/// globbing both "*" and "**" patterns such as "**/*".
/// </summary>
public string Pattern { get; set; } = null!;
/// <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> Run()
{
return this.Run(Array.Empty<Entity>());
}
/// <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 override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
var glob = Glob.Parse(this.Pattern);
IEnumerable<FileEntry> files = this.FileSystem.EnumerateFileEntries("/", "*", SearchOption.AllDirectories)
.Where(x => glob.IsMatch(x.Path.ToString()));
IEnumerable<Entity> entities = files.Select(this.ToEntity);
return entities;
}
public ReadFiles WithFileSystem(IFileSystem value)
{
this.FileSystem = value;
return this;
}
/// <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;
}
}