This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
7 changed files with 784842 additions and 0 deletions

View file

@ -0,0 +1,28 @@
namespace Brutal.Localization.ResX
{
/// <summary>
/// Thrown when the root tag of the ResX file is not &lt;root&gt;.
/// </summary>
public class ResXBadRootTagException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="ResXBadRootTagException"/> class.
/// </summary>
public ResXBadRootTagException() { }
/// <summary>
/// Initializes a new instance of the <see cref="ResXBadRootTagException"/> class.
/// </summary>
/// <param name="message">Exception message</param>
public ResXBadRootTagException(string message)
: base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="ResXBadRootTagException"/> class.
/// </summary>
/// <param name="message">Exception messsage</param>
/// <param name="innerException">Inner exception (if any.)</param>
public ResXBadRootTagException(string message, Exception innerException)
: base(message, innerException) { }
}
}

View file

@ -0,0 +1,180 @@
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace Brutal.Localization.ResX
{
/// <summary>
/// Converts ResX files to other formats.
/// </summary>
public static class ResXConvert
{
private static readonly JsonSerializerOptions s_indentedWriter = new()
{
WriteIndented = true,
};
private static readonly JsonWriterOptions s_unsafeEncoder = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
private static readonly JsonWriterOptions s_defaultEncoder = new()
{
Encoder = JavaScriptEncoder.Default,
};
/// <summary>
/// Converts the ResX file to JSON.
/// </summary>
/// <param name="resx">Input ResX file.</param>
/// <param name="unsafeEncoder">Set to true if ResX file may contain characters other than English.</param>
/// <param name="prettify">Set to true if you don't want the output JSON file to be minified.</param>
/// <returns>JSON representation of the ResX file.</returns>
public static string ToJson(ResXFile resx, bool unsafeEncoder = true, bool prettify = false)
{
using var stream = new MemoryStream();
using var writer = new Utf8JsonWriter(
stream,
unsafeEncoder ? s_unsafeEncoder : s_defaultEncoder
);
writer.WriteStartArray();
foreach (var data in resx.DataDictionary.Values)
{
writer.WriteStartObject();
writer.WriteString("name"u8, data.Name);
writer.WriteString("value"u8, data.Value);
writer.WriteString("comment"u8, data.Comment);
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.Flush();
return JsonPrettify(Encoding.UTF8.GetString(stream.ToArray()), prettify);
}
/// <summary>
/// Converts the ResX file to JSON, asynchronously.
/// </summary>
/// <param name="resx">Input ResX file.</param>
/// <param name="unsafeEncoder">Set to true if ResX file may contain characters other than English.</param>
/// <param name="prettify">Set to true if you don't want the output JSON file to be minified.</param>
/// <returns>JSON representation of the ResX file.</returns>
public static async Task<string> ToJsonAsync(
ResXFile resx,
bool unsafeEncoder = true,
bool prettify = false
)
{
await using var stream = new MemoryStream();
await using var writer = new Utf8JsonWriter(
stream,
unsafeEncoder ? s_unsafeEncoder : s_defaultEncoder
);
writer.WriteStartArray();
foreach (var data in resx.DataDictionary.Values)
{
writer.WriteStartObject();
writer.WriteString("name"u8, data.Name);
writer.WriteString("value"u8, data.Value);
writer.WriteString("comment"u8, data.Comment);
writer.WriteEndObject();
}
writer.WriteEndArray();
await writer.FlushAsync();
return JsonPrettify(Encoding.UTF8.GetString(stream.ToArray()), prettify);
}
/// <summary>
/// Converts the ResX file to Markdown.
/// </summary>
/// <param name="resx">Input ResX file.</param>
/// <returns>A Markdown representation of the ResX document.</returns>
public static string ToMarkdown(ResXFile resx)
{
var builder = new StringBuilder();
builder.AppendLine("# Converted result from a ResX file");
builder.AppendLine("*Auto-generated by ResXNET v1.0.0*");
foreach (var data in resx.DataDictionary.Values)
{
builder.AppendLine($"### {data.Name}");
builder.AppendLine(
$"*Value*: **{data.Value}**; *comment*: **{data.Comment ?? "null"}**"
);
}
return builder.ToString();
}
/// <summary>
/// Converts the ResX file to C#.
/// </summary>
/// <param name="resx">Input ResX file to process.</param>
/// <returns>C# representation of all data fields of the ResX file.</returns>
public static string ToCSharp(ResXFile resx)
{
var builder = new StringBuilder();
builder.AppendLine("internal class Class1");
builder.AppendLine("{");
foreach (var data in resx.DataDictionary.Values)
{
if (data.Comment != null)
{
builder.AppendLine(" /// <summary>");
builder.AppendLine($" /// {data.Comment}");
builder.AppendLine(" /// </summary>");
}
string name = new(
Capitalize(data.Name)
.Where(ch =>
(
!char.IsWhiteSpace(ch)
&& !char.IsPunctuation(ch)
&& !char.IsControl(ch)
)
|| ch == '_'
)
.ToArray()
);
builder.AppendLine($" public string {Capitalize(name)} = \"{data.Value}\";");
}
return builder.ToString();
}
// source:
// https://stackoverflow.com/a/4405876/21072788
// CC BY-SA 4.0
private static string Capitalize(this string input) =>
input switch
{
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException(
$"{nameof(input)} cannot be empty",
nameof(input)
),
_ => string.Concat(input[0].ToString().ToUpper(), input.AsSpan(1)),
};
// source: https://stackoverflow.com/a/67928315/21072788
// CC BY-SA 4.0
private static string JsonPrettify(this string json, bool reallyPrettify = true)
{
if (!reallyPrettify)
{
return json;
}
using var jDoc = JsonDocument.Parse(json);
return JsonSerializer.Serialize(jDoc, s_indentedWriter);
}
}
}

View file

@ -0,0 +1,9 @@
namespace Brutal.Localization.ResX;
/// <summary>
/// Represents a single &lt;data&gt; tag in a text ResX file.
/// </summary>
/// <param name="Name">Name of the data.</param>
/// <param name="Value">Value of the data.</param>
/// <param name="Comment">Optional comment to go along with the data.</param>
public record ResXData(string Name, string Value, string? Comment);

View file

@ -0,0 +1,130 @@
// NOTE: RootHeader is a multi-line verbatim literal, so its compiled value embeds the
// source file's line endings. It must stay LF to match the public API baseline -
// enforced by .gitattributes (*.cs text eol=lf).
namespace Brutal.Localization.ResX
{
public partial class ResXFile
{
/// <summary>
/// The header of the &lt;root&gt; tag.
/// </summary>
public const string RootHeader =
@"<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name=""resmimetype"">text/microsoft-resx</resheader>
<resheader name=""version"">2.0</resheader>
<resheader name=""reader"">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name=""writer"">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name=""Name1""><value>this is my long string</value><comment>this is a comment</comment></data>
<data name=""Color1"" type=""System.Drawing.Color, System.Drawing"">Blue</data>
<data name=""Bitmap1"" mimetype=""application/x-microsoft.net.object.binary.base64"">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name=""Icon1"" type=""System.Drawing.Icon, System.Drawing"" mimetype=""application/x-microsoft.net.object.bytearray.base64"">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of ""resheader"" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id=""root"" xmlns="""" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
<xsd:import namespace=""http://www.w3.org/XML/1998/namespace"" />
<xsd:element name=""root"" msdata:IsDataSet=""true"">
<xsd:complexType>
<xsd:choice maxOccurs=""unbounded"">
<xsd:element name=""metadata"">
<xsd:complexType>
<xsd:sequence>
<xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" />
</xsd:sequence>
<xsd:attribute name=""name"" use=""required"" type=""xsd:string"" />
<xsd:attribute name=""type"" type=""xsd:string"" />
<xsd:attribute name=""mimetype"" type=""xsd:string"" />
<xsd:attribute ref=""xml:space"" />
</xsd:complexType>
</xsd:element>
<xsd:element name=""assembly"">
<xsd:complexType>
<xsd:attribute name=""alias"" type=""xsd:string"" />
<xsd:attribute name=""name"" type=""xsd:string"" />
</xsd:complexType>
</xsd:element>
<xsd:element name=""data"">
<xsd:complexType>
<xsd:sequence>
<xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
<xsd:element name=""comment"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""2"" />
</xsd:sequence>
<xsd:attribute name=""name"" type=""xsd:string"" use=""required"" msdata:Ordinal=""1"" />
<xsd:attribute name=""type"" type=""xsd:string"" msdata:Ordinal=""3"" />
<xsd:attribute name=""mimetype"" type=""xsd:string"" msdata:Ordinal=""4"" />
<xsd:attribute ref=""xml:space"" />
</xsd:complexType>
</xsd:element>
<xsd:element name=""resheader"">
<xsd:complexType>
<xsd:sequence>
<xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
</xsd:sequence>
<xsd:attribute name=""name"" type=""xsd:string"" use=""required"" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name=""resmimetype"">
<value>text/microsoft-resx</value>
</resheader>
<resheader name=""version"">
<value>2.0</value>
</resheader>
<resheader name=""reader"">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name=""writer"">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
";
}
}

View file

@ -0,0 +1,184 @@
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace Brutal.Localization.ResX
{
// The ResX reading and writing code is taken from a github project. It should be thought of as
// a temporary solution to reading and writing ResX files that support strings only.
// https://github.com/winscripter/resx-net
// The source code is under the MIT License. See the file ResX.Net.LICENSE under the Resources.ResX.NET folder.
/// <summary>
/// Parses and builds a ResX file. This class cannot be inherited.
/// </summary>
/// <remarks>
/// The code for ResX reading and writing is provided by github project https://github.com/winscripter/resx-net under
/// the following license.
///
/// MIT License
///
/// Copyright (c) 2024 winscripter
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
/// </remarks>
public sealed partial class ResXFile
{
/// <summary>
/// A list of descendant ResX data tags.
/// </summary>
/// inside an IResourceWriter etc.
public Dictionary<string, ResXData> DataDictionary { get; private set; }
/// <summary>
/// Create a ResXFile instance and populate it with data from an IEnumerable.
/// </summary>
/// <param name="dataList">IEnumerable&lt;<see cref="ResXData"/>&gt; to populate with.</param>
public ResXFile(IEnumerable<ResXData> dataList)
{
DataDictionary = dataList.ToDictionary<ResXData, string>(item => item.Name);
}
/// <summary>
/// Create a ResXFile instance and populate it with data from Dictionary.
/// </summary>
/// <param name="dataList">Dictionary&lt;string, <see cref="ResXData"/>&gt; to populate with.</param>
public ResXFile(Dictionary<string, ResXData> dataList)
{
DataDictionary = dataList;
}
/// <summary>
/// Initializes a new instance of the <see cref="ResXFile"/> class.
/// </summary>
public ResXFile()
: this(new List<ResXData>()) { }
/// <summary>
/// Builds a ResX formatted string from the contents of the <see cref="ResXFile"/>.
/// </summary>
/// <returns>string content of ResX.</returns>
public string Build()
{
var builder = new StringBuilder();
builder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
builder.AppendLine("<root>");
builder.AppendLine(
string.Join(
"\r\n",
RootHeader
.Split(["\r\n"], StringSplitOptions.None)
.Select(line =>
{
var nestedBuilder = new StringBuilder();
nestedBuilder.Append(" ");
nestedBuilder.Append(line);
return nestedBuilder.ToString();
})
)
);
foreach (var data in DataDictionary.Values)
{
var dataElement = new XElement(
"data",
new XAttribute("name", data.Name),
new XAttribute(XNamespace.Xml + "space", "preserve"),
new XElement("value", data.Value)
);
if (data.Comment is not null)
{
dataElement.Add(new XElement("comment", data.Comment));
}
builder.AppendLine(dataElement.ToString());
}
builder.AppendLine("</root>");
return builder.ToString();
}
/// <summary>
/// Parses the raw plain text of the ResX file into an enumerable of
/// <see cref="ResXData"/>.
/// </summary>
/// <param name="rawText">Input plain text of the ResX file.</param>
/// <returns>An enumerable of <see cref="ResXData"/>.</returns>
/// <exception cref="XmlException">In this method, thrown when the root tag is missing.</exception>
/// <exception cref="ResXBadRootTagException">In this method, thrown when the root tag name is not "root".</exception>
/// <exception cref="ResXNoAttributeException">In this method, thrown when the data tag does not have the required attribute.</exception>
/// <exception cref="ResXNoValueException">In this method, thrown when the data tag does not have a child &lt;value&gt; tag.</exception>
public static Dictionary<string, ResXData> Parse(string rawText)
{
var rootTag =
XDocument.Parse(rawText).Root ?? throw new XmlException("Root tag is missing");
if (!rootTag.Name.LocalName.Equals("root", StringComparison.CurrentCultureIgnoreCase))
{
throw new ResXBadRootTagException(
$"Root tag of the ResX file is \"{rootTag.Name.LocalName}\", but expected \"root\""
);
}
var resxData = new Dictionary<string, ResXData>();
foreach (var descendant in rootTag.Elements())
{
if (
!descendant.Name.LocalName.Equals(
"data",
StringComparison.CurrentCultureIgnoreCase
)
)
{
continue;
}
var nameAttribute =
descendant.Attribute("name")?.Value
?? throw new ResXNoAttributeException("No attribute named \"name\"");
var value =
descendant
.Descendants()
.FirstOrDefault(tag =>
tag.Name.LocalName.Equals(
"value",
StringComparison.CurrentCultureIgnoreCase
)
)
?.Value
?? throw new ResXNoValueException(
"Data does not have descendant element of type \"value\""
);
var comment = descendant
.Descendants()
.FirstOrDefault(tag =>
tag.Name.LocalName.Equals(
"comment",
StringComparison.CurrentCultureIgnoreCase
)
)
?.Value;
resxData.Add(nameAttribute, new ResXData(nameAttribute, value, comment));
}
return resxData;
}
}
}

View file

@ -0,0 +1,28 @@
namespace Brutal.Localization.ResX
{
/// <summary>
/// Thrown when a ResX &lt;data&gt; tag has no crucial attribute.
/// </summary>
public class ResXNoAttributeException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="ResXNoAttributeException"/> class.
/// </summary>
public ResXNoAttributeException() { }
/// <summary>
/// Initializes a new instance of the <see cref="ResXNoAttributeException"/> class.
/// </summary>
/// <param name="message">Exception message.</param>
public ResXNoAttributeException(string? message)
: base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="ResXNoAttributeException"/> class.
/// </summary>
/// <param name="message">Exception message.</param>
/// <param name="innerException">Inner exception (if any.)</param>
public ResXNoAttributeException(string? message, Exception? innerException)
: base(message, innerException) { }
}
}

View file

@ -0,0 +1,28 @@
namespace Brutal.Localization.ResX
{
/// <summary>
/// Thrown when a ResX &lt;data&gt; tag has no descendant XML tag of type &lt;value&gt;.
/// </summary>
public class ResXNoValueException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="ResXNoValueException"/> class.
/// </summary>
public ResXNoValueException() { }
/// <summary>
/// Initializes a new instance of the <see cref="ResXNoValueException"/> class.
/// </summary>
/// <param name="message">Exception message.</param>
public ResXNoValueException(string? message)
: base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="ResXNoValueException"/> class.
/// </summary>
/// <param name="message">Exception message.</param>
/// <param name="innerException">Inner exception (if any.)</param>
public ResXNoValueException(string? message, Exception? innerException)
: base(message, innerException) { }
}
}