|
| 1 | +using System.Text.RegularExpressions; |
| 2 | + |
| 3 | +namespace Yafc.I18n.Generator; |
| 4 | + |
| 5 | +internal partial class SourceGenerator { |
| 6 | + private static readonly Dictionary<string, int> localizationKeys = []; |
| 7 | + |
| 8 | + private static void Main() { |
| 9 | + // Find the solution root directory |
| 10 | + string rootDirectory = Environment.CurrentDirectory; |
| 11 | + while (!Directory.Exists(Path.Combine(rootDirectory, ".git"))) { |
| 12 | + rootDirectory = Path.GetDirectoryName(rootDirectory)!; |
| 13 | + } |
| 14 | + Environment.CurrentDirectory = rootDirectory; |
| 15 | + |
| 16 | + HashSet<string> keys = []; |
| 17 | + HashSet<string> referencedKeys = []; |
| 18 | + |
| 19 | + using MemoryStream classesMemory = new(), stringsMemory = new(); |
| 20 | + using (StreamWriter classes = new(classesMemory, leaveOpen: true), strings = new(stringsMemory, leaveOpen: true)) { |
| 21 | + |
| 22 | + // Always generate the LocalizableString and LocalizableString0 classes |
| 23 | + classes.WriteLine(""" |
| 24 | + using System.Diagnostics.CodeAnalysis; |
| 25 | +
|
| 26 | + namespace Yafc.I18n; |
| 27 | +
|
| 28 | + #nullable enable |
| 29 | +
|
| 30 | + /// <summary> |
| 31 | + /// The base class for YAFC's localizable UI strings. |
| 32 | + /// </summary> |
| 33 | + public abstract class LocalizableString { |
| 34 | + private protected readonly string key; |
| 35 | +
|
| 36 | + private protected LocalizableString(string key) => this.key = key; |
| 37 | +
|
| 38 | + /// <summary> |
| 39 | + /// Localize this string using an arbitrary number of parameters. Insufficient parameters will cause the localization to fail, |
| 40 | + /// and excess parameters will be ignored. |
| 41 | + /// </summary> |
| 42 | + /// <param name="args">An array of parameter values.</param> |
| 43 | + /// <returns>The localized string</returns> |
| 44 | + public string Localize(params object[] args) => LocalisedStringParser.ParseKey(key, args) ?? "Key not found: " + key; |
| 45 | + } |
| 46 | +
|
| 47 | + /// <summary> |
| 48 | + /// A localizable UI string that needs 0 parameters for localization. |
| 49 | + /// These strings will implicitly localize when appropriate. |
| 50 | + /// </summary> |
| 51 | + public sealed class LocalizableString0 : LocalizableString { |
| 52 | + internal LocalizableString0(string key) : base(key) { } |
| 53 | +
|
| 54 | + /// <summary> |
| 55 | + /// Localize this string. |
| 56 | + /// </summary> |
| 57 | + /// <returns>The localized string</returns> |
| 58 | + public string L() => LocalisedStringParser.ParseKey(key, []) ?? "Key not found: " + key; |
| 59 | +
|
| 60 | + /// <summary> |
| 61 | + /// Implicitly localizes a zero-parameter localizable string. |
| 62 | + /// </summary> |
| 63 | + /// <param name="lString">The zero-parameter string to be localized</param> |
| 64 | + [return: NotNullIfNotNull(nameof(lString))] |
| 65 | + public static implicit operator string?(LocalizableString0? lString) => lString?.L(); |
| 66 | + } |
| 67 | + """); |
| 68 | + |
| 69 | + HashSet<int> declaredArities = [0]; |
| 70 | + |
| 71 | + // Generate the beginning of the LSs class |
| 72 | + strings.WriteLine(""" |
| 73 | + namespace Yafc.I18n; |
| 74 | +
|
| 75 | + /// <summary> |
| 76 | + /// A class containing localizable strings for each key defined in the English localization file. This name should be read as |
| 77 | + /// <c>LocalizableStrings</c>. It is aggressively abbreviated to help keep lines at a reasonable length. |
| 78 | + /// </summary> |
| 79 | + /// <remarks>This class is auto-generated. To add new localizable strings, add them to Yafc/Data/locale/en/yafc.cfg |
| 80 | + /// and build the solution.</remarks> |
| 81 | + public static class LSs { |
| 82 | + """); |
| 83 | + |
| 84 | + // For each key in locale/en/*.* |
| 85 | + foreach (string file in Directory.EnumerateFiles(Path.Combine(rootDirectory, "Yafc/Data/locale/en"))) { |
| 86 | + using Stream stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); |
| 87 | + foreach (var (category, key, v) in FactorioLocalization.Read(stream)) { |
| 88 | + string value = v; // iteration variables are read-only; make value writable. |
| 89 | + int parameterCount = 0; |
| 90 | + foreach (Match match in FindParameters().Matches(value)) { |
| 91 | + parameterCount = Math.Max(parameterCount, int.Parse(match.Groups[1].Value)); |
| 92 | + } |
| 93 | + |
| 94 | + // If we haven't generated it yet, generate the LocalizableString<parameterCount> class |
| 95 | + if (declaredArities.Add(parameterCount)) { |
| 96 | + classes.WriteLine($$""" |
| 97 | +
|
| 98 | + /// <summary> |
| 99 | + /// A localizable string that needs {{parameterCount}} parameters for localization. |
| 100 | + /// </summary> |
| 101 | + public sealed class LocalizableString{{parameterCount}} : LocalizableString { |
| 102 | + internal LocalizableString{{parameterCount}}(string key) : base(key) { } |
| 103 | + |
| 104 | + /// <summary> |
| 105 | + /// Localize this string. |
| 106 | + /// </summary> |
| 107 | + {{string.Join(Environment.NewLine, Enumerable.Range(1, parameterCount).Select(n => $" /// <param name=\"p{n}\">The value to use for parameter __{n}__ when localizing this string.</param>"))}} |
| 108 | + /// <returns>The localized string</returns> |
| 109 | + public string L({{string.Join(", ", Enumerable.Range(1, parameterCount).Select(n => $"object p{n}"))}}) |
| 110 | + => LocalisedStringParser.ParseKey(key, [{{string.Join(", ", Enumerable.Range(1, parameterCount).Select(n => $"p{n}"))}}]) ?? "Key not found: " + key; |
| 111 | + } |
| 112 | + """); |
| 113 | + } |
| 114 | + |
| 115 | + string pascalCasedKey = string.Join("", key.Split('-').Select(s => char.ToUpperInvariant(s[0]) + s[1..])); |
| 116 | + keys.Add(key); |
| 117 | + |
| 118 | + foreach (Match match in FindReferencedKeys().Matches(value)) { |
| 119 | + referencedKeys.Add(match.Groups[1].Value); |
| 120 | + } |
| 121 | + |
| 122 | + if (value.Length > 70) { |
| 123 | + value = value[..70] + "..."; |
| 124 | + } |
| 125 | + value = value.Replace("&", "&").Replace("<", "<"); |
| 126 | + |
| 127 | + // Generate the read-only PascalCasedKeyName field. |
| 128 | + strings.WriteLine($$""" |
| 129 | + /// <summary> |
| 130 | + /// Gets a string that will localize to a value resembling "{{value}}" |
| 131 | + /// </summary> |
| 132 | + """); |
| 133 | +#if DEBUG |
| 134 | + strings.WriteLine($" public static LocalizableString{parameterCount} {pascalCasedKey} {{ get; }} = new(\"{category}.{key}\");"); |
| 135 | +#else |
| 136 | + // readonly fields are much smaller than read-only properties, but VS doesn't provide inline reference counts for them. |
| 137 | + strings.WriteLine($" public static readonly LocalizableString{parameterCount} {pascalCasedKey} = new(\"{category}.{key}\");"); |
| 138 | +#endif |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + foreach (string? undefinedKey in referencedKeys.Except(keys)) { |
| 143 | + strings.WriteLine($"#error Found a reference to __YAFC__{undefinedKey}__, which is not defined."); |
| 144 | + } |
| 145 | + // end of class LLs |
| 146 | + strings.WriteLine("}"); |
| 147 | + } |
| 148 | + |
| 149 | + ReplaceIfChanged("Yafc.I18n/LocalizableStringClasses.g.cs", classesMemory); |
| 150 | + ReplaceIfChanged("Yafc.I18n/LocalizableStrings.g.cs", stringsMemory); |
| 151 | + } |
| 152 | + |
| 153 | + // Replace the files only if the new content is different than the old content. |
| 154 | + private static void ReplaceIfChanged(string filePath, MemoryStream newContent) { |
| 155 | + newContent.Position = 0; |
| 156 | + if (!File.Exists(filePath) || File.ReadAllText(filePath) != new StreamReader(newContent, leaveOpen: true).ReadToEnd()) { |
| 157 | + File.WriteAllBytes(filePath, newContent.ToArray()); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + [GeneratedRegex("__(\\d+)__")] |
| 162 | + private static partial Regex FindParameters(); |
| 163 | + [GeneratedRegex("__YAFC__([a-zA-Z0-9_-]+)__")] |
| 164 | + private static partial Regex FindReferencedKeys(); |
| 165 | +} |
0 commit comments