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; /// /// A module that reads files from the file system and wraps them in an /// entity with the following components: UPath, IContent. /// [WithProperties] public partial class ReadFiles : FileSystemOperationBase { private readonly IValidator validator; public ReadFiles( IValidator validator, IFileSystem fileSystem) : base(fileSystem) { this.validator = validator; } /// /// Gets or sets the file pattern to retrieve fields. This supports /// globbing both "*" and "**" patterns such as "**/*". /// public string Pattern { get; set; } = null!; /// /// Reads all files from the file system, filtering them out by the /// minimatch pattern (as defined by DotNet.Blob). /// /// A populated collection of entities. public IEnumerable Run() { return this.Run(Array.Empty()); } /// /// Reads all files from the file system, filtering them out by the /// minimatch pattern (as defined by DotNet.Blob). /// /// A populated collection of entities. public override IEnumerable Run(IEnumerable input) { this.validator.ValidateAndThrow(this); var glob = Glob.Parse(this.Pattern); IEnumerable files = this.FileSystem.EnumerateFileEntries("/", "*", SearchOption.AllDirectories) .Where(x => glob.IsMatch(x.Path.ToString())); IEnumerable entities = files.Select(this.ToEntity); return entities; } public ReadFiles WithFileSystem(IFileSystem value) { this.FileSystem = value; return this; } /// /// 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. /// /// The Zio file entry. /// An Entity with appropriate content. private Entity ToEntity(FileEntry file) { Entity entity = new Entity().Set(file.Path) .SetBinaryContent(new FileEntryBinaryContent(file)); return entity; } }