83 lines
2.5 KiB
C#
83 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Gallium;
|
|
using Serilog;
|
|
using Zio;
|
|
|
|
namespace 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 : FileSystemOperation, INitrideOperation
|
|
{
|
|
private readonly ILogger logger;
|
|
|
|
public ClearDirectory(
|
|
ILogger logger,
|
|
IFileSystem fileSystem)
|
|
: base(fileSystem)
|
|
{
|
|
this.logger = logger.ForContext<ClearDirectory>();
|
|
}
|
|
|
|
/// <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 IEnumerable<Entity> Run(IEnumerable<Entity> input)
|
|
{
|
|
// 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;
|
|
}
|
|
}
|
|
}
|