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

84 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using Gallium;
using Nitride.Contents;
using Zio;
namespace Nitride.Markdown
{
/// <summary>
/// An operation that identifies Markdown files by their common extensions
/// and converts them to text input while also adding the IsMarkdown
/// component to identify them.
/// </summary>
[WithProperties]
public partial class IdentifyMarkdown : INitrideOperation
{
public IdentifyMarkdown()
{
this.IsMarkdownTest = DefaultIsMarkdown;
}
public Func<Entity, UPath, bool> IsMarkdownTest { get; set; }
/// <inheritdoc />
public IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
return input
.ForEachEntity<UPath, ITextContent>(
(entity, path, _) =>
{
// If we aren't a Markdown file, then there is nothing
// we can do about that.
if (!this.IsMarkdownTest(entity, path))
{
return entity;
}
// We are already text, so just mark it as Markdown.
entity = entity
.Set(IsMarkdown.Instance);
return entity;
})
.ForEachEntity<UPath, IBinaryContent>(
(entity, path, binary) =>
{
// If we aren't a Markdown file, then there is nothing
// we can do about that.
if (!this.IsMarkdownTest(entity, path))
{
return entity;
}
// Convert the file as a binary.
if (binary is ITextContentConvertable textConvertable)
{
entity = entity
.SetTextContent(textConvertable.ToTextContent())
.Set(IsMarkdown.Instance);
}
else
{
throw new InvalidOperationException(
"Cannot convert a binary content to a "
+ "text without ITextContentConvertable.");
}
return entity;
});
}
private static bool DefaultIsMarkdown(Entity entity, UPath path)
{
return (path.GetExtensionWithDot() ?? string.Empty)
.ToLowerInvariant() switch
{
".md" => true,
".markdown" => true,
_ => false,
};
}
}
}