mfgames-cil/src/MfGames.Nitride.Markdown/RewriteLinkToIndexPath.cs
D. Moonfire 23a65c8674
All checks were successful
deploy / deploy (push) Successful in 41m4s
feat: added a Markdown transformer to convert links to index paths
2024-03-18 22:27:42 -05:00

56 lines
1.5 KiB
C#

using System.Text.RegularExpressions;
using Markdig.Syntax.Inlines;
using MfGames.Gallium;
namespace MfGames.Nitride.Markdown;
/// <summary>
/// An operation that rewrites link paths to be directory indexes.
/// </summary>
public class RewriteLinkToIndexPath : IOperation
{
private static readonly Regex IndexRegex = new(@"/index\.(markdown|md|html|htm)$");
private readonly RewriteMarkdownLink rewrite;
public RewriteLinkToIndexPath(RewriteMarkdownLink rewrite)
{
this.rewrite = rewrite;
this.rewrite.OnLinkCallback = this.OnLinkCallback;
}
/// <inheritdoc />
public IEnumerable<Entity> Run(
IEnumerable<Entity> input,
CancellationToken cancellationToken = default
)
{
return this.rewrite.Run(input, cancellationToken);
}
private void OnLinkCallback(LinkInline link)
{
// Ignore blank links (they could happen).
string? url = link.Url;
if (string.IsNullOrEmpty(url))
{
return;
}
// We only want links that start with a period or are relative to the
// current directory. Ideally, we don't want links that are remote URLs.
// This is a simplistic version.
if (url.Contains("://"))
{
return;
}
// Check to see what the path ends with something we can map.
if (IndexRegex.IsMatch(url))
{
link.Url = IndexRegex.Replace(url, "/");
}
}
}