1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-22 21:38:47 +00:00
X10D/tools/SourceGenerator/EmojiRegexGenerator.cs

70 lines
2.4 KiB
C#
Raw Normal View History

2023-08-26 17:11:29 +00:00
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace SourceGenerator;
[Generator]
internal sealed class EmojiRegexGenerator : ISourceGenerator
{
// ReSharper disable once IdentifierTypo
private const string TwemojiRegexUrl = "https://raw.githubusercontent.com/twitter/twemoji-parser/master/src/lib/regex.js";
private static readonly HttpClient HttpClient = new();
private string _emojiRegex = string.Empty;
/// <inheritdoc />
public void Initialize(GeneratorInitializationContext context)
{
string response = HttpClient.GetStringAsync(TwemojiRegexUrl).GetAwaiter().GetResult();
var regex = new Regex(@"export default /(?<regex>.+)/g;", RegexOptions.Compiled, Regex.InfiniteMatchTimeout);
using var reader = new StringReader(response);
while (reader.ReadLine() is { } line)
{
if (!line.StartsWith("export default /"))
{
continue;
}
Match match = regex.Match(line);
if (!match.Success)
{
continue;
}
_emojiRegex = $"^{match.Groups["regex"].Value}$";
break;
}
}
/// <inheritdoc />
public void Execute(GeneratorExecutionContext context)
{
if (string.IsNullOrEmpty(_emojiRegex))
{
return;
}
var builder = new StringBuilder();
builder.AppendLine("// This file was auto-generated by the X10D source generator");
builder.AppendLine("// Do not edit this file manually!");
builder.AppendLine();
builder.AppendLine("using System.Text.RegularExpressions;");
builder.AppendLine();
builder.AppendLine("namespace X10D.Text;");
builder.AppendLine();
builder.AppendLine("internal static class EmojiRegex");
builder.AppendLine("{");
builder.AppendLine(" internal static readonly Regex Value = new Regex(");
builder.AppendLine($" @\"{_emojiRegex}\",");
// ReSharper disable once StringLiteralTypo
builder.AppendLine(" RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline");
builder.AppendLine(" );");
builder.AppendLine("}");
context.AddSource("EmojiRegex.g.cs", SourceText.From(builder.ToString(), Encoding.UTF8));
}
}