2022-05-07 22:37:14 +00:00
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
|
using Microsoft.CodeAnalysis;
|
|
|
|
|
using Microsoft.CodeAnalysis.Text;
|
|
|
|
|
|
|
|
|
|
namespace X10D.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();
|
2023-03-28 14:44:27 +00:00
|
|
|
|
var regex = new Regex(@"export default /(?<regex>.+)/g;", RegexOptions.Compiled, Regex.InfiniteMatchTimeout);
|
2022-05-07 22:37:14 +00:00
|
|
|
|
using var reader = new StringReader(response);
|
|
|
|
|
|
|
|
|
|
while (reader.ReadLine() is { } line)
|
|
|
|
|
{
|
|
|
|
|
if (!line.StartsWith("export default /"))
|
|
|
|
|
{
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-28 14:44:27 +00:00
|
|
|
|
Match match = regex.Match(line);
|
2022-05-07 22:37:14 +00:00
|
|
|
|
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 X10D.SourceGenerator");
|
|
|
|
|
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));
|
|
|
|
|
}
|
|
|
|
|
}
|