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

77 lines
2.1 KiB
C#
Raw Normal View History

2021-09-07 05:15:45 +00:00
using System;
using System.Collections.Generic;
using FluentValidation;
2021-09-07 05:15:45 +00:00
using Gallium;
2021-09-07 05:15:45 +00:00
using Nitride.Contents;
2021-09-07 05:15:45 +00:00
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 : IOperation
2021-09-07 05:15:45 +00:00
{
private readonly IValidator<IdentifyMarkdown> validator;
public IdentifyMarkdown(IValidator<IdentifyMarkdown> validator)
{
this.validator = validator;
}
public Func<Entity, UPath, bool> IsMarkdownTest { get; set; } = null!;
/// <inheritdoc />
public IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
return input.ForEachEntity<UPath, ITextContent>(this.MarkTextEntities)
.ForEachEntity<UPath, IBinaryContent>(this.MarkBinaryEntities);
}
private Entity MarkBinaryEntities(Entity entity, UPath path, IBinaryContent binary)
{
// If we aren't a Markdown file, then there is nothing we can do about that.
if (!this.IsMarkdownTest(entity, path))
{
return entity;
}
2021-09-07 05:15:45 +00:00
// Convert the file as a binary.
if (binary is ITextContentConvertable textConvertable)
2021-09-07 05:15:45 +00:00
{
entity = entity.SetTextContent(textConvertable.ToTextContent()).Set(IsMarkdown.Instance);
2021-09-07 05:15:45 +00:00
}
else
{
throw new InvalidOperationException(
"Cannot convert a binary content to a text without ITextContentConvertable.");
}
return entity;
}
2021-09-07 05:15:45 +00:00
private Entity MarkTextEntities(Entity entity, UPath path, ITextContent _)
{
// If we aren't a Markdown file, then there is nothing
// we can do about that.
if (!this.IsMarkdownTest(entity, path))
2021-09-07 05:15:45 +00:00
{
return entity;
2021-09-07 05:15:45 +00:00
}
// We are already text, so just mark it as Markdown.
entity = entity.Set(IsMarkdown.Instance);
return entity;
2021-09-07 05:15:45 +00:00
}
}