using System; using System.Collections.Generic; using FluentValidation; using MfGames.Gallium; using Serilog; using Zio; namespace MfGames.Nitride.IO.Directories; /// /// A Nitride operation that removes the contents of a directory but not /// the directory itself. This is used because some tools don't handle /// when the root directory is removed. /// This will create the top-level directory if it doesn't exist. /// [WithProperties] public partial class ClearDirectory : FileSystemOperationBase, IOperation { private readonly IValidator validator; public ClearDirectory( IValidator validator, IFileSystem fileSystem, ILogger logger) : base(fileSystem) { this.Logger = logger; this.validator = validator; } public ILogger Logger { get; set; } /// /// Gets or sets the path of the directory to clear. /// public UPath? Path { get; set; } public IEnumerable Run() { return this.Run(new List()); } /// public override IEnumerable Run(IEnumerable input) { this.validator.ValidateAndThrow(this); // This really isn't an input-type of operation, but it can fit // inside one to keep a pattern. if (!this.Path.HasValue) { throw new InvalidOperationException( nameof(ClearDirectory) + "cannot be used without setting the path either by the" + "factory method, the constructor, the property, or " + "SetPath method."); } // See if the directory exists. If it doesn't, then we make it. UPath path = this.Path.Value; if (!this.FileSystem.DirectoryExists(path)) { this.Logger.Information("Creating the directory {Path}", path); this.FileSystem.CreateDirectory(path); } // Clear out the contents. IEnumerable files = this.FileSystem.EnumerateFiles(path); IEnumerable directories = this.FileSystem.EnumerateDirectories(path); foreach (UPath file in files) { this.FileSystem.DeleteFile(file); } foreach (UPath directory in directories) { this.FileSystem.DeleteDirectory(directory, true); } // Just pass the input on. return input; } public ClearDirectory WithFileSystem(IFileSystem value) { this.FileSystem = value; return this; } }