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#
Raw Normal View History

2021-09-07 05:15:45 +00:00
using System;
using System.Collections.Generic;
using FluentValidation;
2022-09-06 05:53:22 +00:00
using MfGames.Gallium;
2021-09-07 05:15:45 +00:00
using Serilog;
2021-09-07 05:15:45 +00:00
using Zio;
2022-09-06 05:53:22 +00:00
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
2021-09-07 05:15:45 +00:00
{
private readonly IValidator<ClearDirectory> validator;
2022-07-09 04:52:10 +00:00
public ClearDirectory(
IValidator<ClearDirectory> validator,
IFileSystem fileSystem,
ILogger logger)
: base(fileSystem)
{
this.Logger = logger;
this.validator = validator;
}
public ILogger Logger { get; set; }
2021-09-07 05:15:45 +00:00
/// <summary>
/// Gets or sets the path of the directory to clear.
2021-09-07 05:15:45 +00:00
/// </summary>
public UPath? Path { get; set; }
public IEnumerable<Entity> Run()
2021-09-07 05:15:45 +00:00
{
return this.Run(new List<Entity>());
}
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
2021-09-07 05:15:45 +00:00
// This really isn't an input-type of operation, but it can fit
// inside one to keep a pattern.
if (!this.Path.HasValue)
2021-09-07 05:15:45 +00:00
{
throw new InvalidOperationException(
nameof(ClearDirectory)
+ "cannot be used without setting the path either by the"
+ "factory method, the constructor, the property, or "
+ "SetPath method.");
2021-09-07 05:15:45 +00:00
}
// See if the directory exists. If it doesn't, then we make it.
UPath path = this.Path.Value;
2021-09-07 05:15:45 +00:00
if (!this.FileSystem.DirectoryExists(path))
2021-09-07 05:15:45 +00:00
{
this.Logger.Information("Creating the directory {Path}", path);
this.FileSystem.CreateDirectory(path);
2021-09-07 05:15:45 +00:00
}
// Clear out the contents.
IEnumerable<UPath> files = this.FileSystem.EnumerateFiles(path);
IEnumerable<UPath> directories = this.FileSystem.EnumerateDirectories(path);
foreach (UPath file in files)
2021-09-07 05:15:45 +00:00
{
this.FileSystem.DeleteFile(file);
2021-09-07 05:15:45 +00:00
}
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;
2022-07-09 04:52:10 +00:00
return this;
2021-09-07 05:15:45 +00:00
}
}