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

60 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using Gallium;
using Zio;
namespace Nitride.IO.Paths
{
/// <summary>
/// A pipeline operation that replaces the UPath of the given entity
/// with the results of a lambda output. Entities without a path component
/// are passed on without touching.
/// </summary>
[WithProperties]
public partial class ReplacePaths : INitrideOperation
{
public ReplacePaths()
{
}
public ReplacePaths(Func<Entity, UPath, UPath> replacement)
{
this.Replacement = replacement;
}
/// <summary>
/// Gets or sets the replacement callback to alter the paths.
/// </summary>
public Func<Entity, UPath, UPath>? Replacement { get; set; }
/// <summary>
/// Performs the replacement on the input streams and outputs the
/// resulting entities. Only entities that have had their paths changed
/// will be updated, the others will be passed on as-is.
/// </summary>
/// <param name="input">The list of input entities.</param>
/// <returns>The output entities.</returns>
public IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
if (this.Replacement == null)
{
throw new InvalidOperationException(
"ReplacePaths.Replacement was not set "
+ "(via constructor, property, or SetReplacement) before "
+ "Replace() was called.");
}
return input
.ForEachEntity<UPath>(
(entity, oldPath) =>
{
UPath newPath = this.Replacement(entity, oldPath);
return newPath != oldPath
? entity.Set(newPath)
: entity;
});
}
}
}