| | | 1 | | using System.Text; |
| | | 2 | | |
| | | 3 | | using Microsoft.CodeAnalysis.Text; |
| | | 4 | | |
| | | 5 | | namespace NexusLabs.Needlr.Generators; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Creates <see cref="SourceText"/> for <c>AddSource</c> with line endings normalized |
| | | 9 | | /// to LF. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <remarks> |
| | | 12 | | /// <para> |
| | | 13 | | /// <see cref="StringBuilder.AppendLine()"/> emits <see cref="System.Environment.NewLine"/>, |
| | | 14 | | /// which is CRLF on Windows and LF elsewhere. Generated source therefore differed |
| | | 15 | | /// byte-for-byte between a Windows build and a Linux build of identical input. |
| | | 16 | | /// </para> |
| | | 17 | | /// <para> |
| | | 18 | | /// Normalizing here rather than at the emitters is deliberate: there are roughly 1,272 |
| | | 19 | | /// <c>AppendLine</c> call sites and 16 <c>AddSource</c> boundaries. Every emitter routes |
| | | 20 | | /// through this one choke point, so an emitter added later inherits the guarantee |
| | | 21 | | /// without knowing about it. |
| | | 22 | | /// </para> |
| | | 23 | | /// </remarks> |
| | | 24 | | internal static class GeneratedSourceText |
| | | 25 | | { |
| | | 26 | | /// <summary> |
| | | 27 | | /// Normalizes line endings and wraps the result as UTF-8 <see cref="SourceText"/>. |
| | | 28 | | /// </summary> |
| | | 29 | | internal static SourceText Create(string generatedText) |
| | | 30 | | { |
| | | 31 | | // The only sanctioned SourceText.From in this project. BannedSymbols.txt routes |
| | | 32 | | // every other emitter here so normalization cannot be bypassed. |
| | | 33 | | #pragma warning disable RS0030 |
| | 2147 | 34 | | return SourceText.From(NormalizeLineEndings(generatedText), Encoding.UTF8); |
| | | 35 | | #pragma warning restore RS0030 |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | private static string NormalizeLineEndings(string text) |
| | | 39 | | { |
| | 2147 | 40 | | if (text.IndexOf('\r') < 0) |
| | | 41 | | { |
| | 2147 | 42 | | return text; |
| | | 43 | | } |
| | | 44 | | |
| | 0 | 45 | | return text |
| | 0 | 46 | | .Replace("\r\n", "\n") |
| | 0 | 47 | | .Replace("\r", "\n"); |
| | | 48 | | } |
| | | 49 | | } |