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/Directories/ClearDirectory.cs

97 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using FluentValidation;
using MfGames.Gallium;
using Serilog;
using Zio;
namespace MfGames.Nitride.IO.Directories;
/// <summary>
/// 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.
/// </summary>
[WithProperties]
public partial class ClearDirectory : FileSystemOperationBase, IOperation
{
private readonly IValidator<ClearDirectory> validator;
public ClearDirectory(
IValidator<ClearDirectory> validator,
IFileSystem fileSystem,
ILogger logger)
: base(fileSystem)
{
this.Logger = logger;
this.validator = validator;
}
public ILogger Logger { get; set; }
/// <summary>
/// Gets or sets the path of the directory to clear.
/// </summary>
public UPath? Path { get; set; }
public IEnumerable<Entity> Run()
{
return this.Run(new List<Entity>());
}
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> 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<UPath> files = this.FileSystem.EnumerateFiles(path);
IEnumerable<UPath> 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;
}
}