using System.Collections.Generic;
using System.IO;
using System.Linq;
using DotNet.Globbing;
using Gallium;
using Nitride.Contents;
using Zio;
namespace Nitride.IO.Contents
{
///
/// A module that reads files from the file system and wraps them in an
/// entity with the following components: UPath, IContent.
///
public class ReadFiles : FileSystemOperation
{
public ReadFiles(IFileSystem fileSystem)
: base(fileSystem)
{
}
///
/// Primary method for creating a read file.
///
public delegate ReadFiles Factory(IFileSystem fileSystem);
///
/// Reads all files from the file system and returns them.
///
/// A populated collection of entities.
public IEnumerable 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 files = this.FileSystem
.EnumerateFileEntries(path, searchPattern, search);
IEnumerable entities = files.Select(this.ToEntity);
return entities;
}
///
/// Reads all files from the file system and returns them.
///
/// A populated collection of entities.
public IEnumerable Read(string glob)
{
Glob parsed = Glob.Parse(glob);
return this.Read(parsed);
}
///
/// 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 Read(Glob glob)
{
IEnumerable files = this.FileSystem
.EnumerateFileEntries("/", "*.*", SearchOption.AllDirectories)
.Where(x => glob.IsMatch(x.Path.ToString()));
IEnumerable entities = files.Select(this.ToEntity);
return entities;
}
///
/// 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;
}
}
}