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/Nitride.IO/Paths/MoveToIndexPaths.cs
Dylan R. E. Moonfire 78054ee2a7 feat: initial release
2021-09-07 00:15:45 -05:00

87 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using Gallium;
using Zio;
namespace Nitride.IO.Paths
{
/// <summary>
/// Moves various files to indexes of a direction with the base filename.
/// </summary>
[WithProperties]
public partial class MoveToIndexPaths : INitrideOperation
{
public MoveToIndexPaths()
{
this.CanMoveCallback = DefaultCanMoveCallback;
}
/// <summary>
/// Gets or sets the callback to determine if the file should be moved.
/// This will not be called if the file is already an index.
/// </summary>
public Func<UPath, bool>? CanMoveCallback { get; set; }
/// <summary>
/// Default implement of the operation moves .html, .htm, .md, and
/// .markdown files into their indexes.
/// </summary>
/// <param name="path"></param>
/// <returns>True if the file should move, otherwise false.</returns>
public static bool DefaultCanMoveCallback(UPath path)
{
return path.GetExtensionWithDot() switch
{
".htm" => true,
".html" => true,
".md" => true,
".markdown" => true,
_ => false,
};
}
public IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
if (this.CanMoveCallback == null)
{
throw new InvalidOperationException(
nameof(MoveToIndexPaths)
+ ".CanMoveCallback was not set "
+ "(via constructor, property, or SetCanMoveCallback) before "
+ "Run() was called.");
}
ReplacePaths replacePaths = new ReplacePaths()
.WithReplacement(this.RunReplacement);
return replacePaths.Run(input);
}
private UPath RunReplacement(Entity _, UPath path)
{
// See if we are already an index. If that is true, then we don't
// have to move any further.
string? nameWithoutExtension = path.GetNameWithoutExtension();
if (nameWithoutExtension is null or "index")
{
return path;
}
// See if the path should be moved. If it can't, then just stop
// processing.
if (!this.CanMoveCallback!.Invoke(path))
{
return path;
}
// Move the file to an index.
UPath parent = path.GetDirectory();
string? extension = path.GetExtensionWithDot();
string index = "index" + extension;
return parent / nameWithoutExtension / index;
}
}
}