| | | 1 | | #region Usings |
| | | 2 | | using System.Security.Cryptography; |
| | | 3 | | using System.Text; |
| | | 4 | | #endregion |
| | | 5 | | |
| | | 6 | | namespace ZhEaIsNsAaBn.DbSeeder; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// The checksum stored in the history table: SHA-256 over a migration's manifest and table files, with line endings nor |
| | | 10 | | /// and any UTF-8 BOM removed, so a CRLF checkout hashes the same as an LF one. |
| | | 11 | | /// </summary> |
| | | 12 | | public static class SeedChecksum |
| | | 13 | | { |
| | | 14 | | /// <summary>The manifest file name inside a migration folder.</summary> |
| | | 15 | | public const string ManifestFile = "manifest.json"; |
| | | 16 | | |
| | | 17 | | |
| | | 18 | | /// <summary>Computes the checksum. Files are hashed by name (<c>manifest.json</c> first, then ordinal order), name |
| | | 19 | | /// <param name="files">File name (no folder) and text of the manifest and each table file.</param> |
| | | 20 | | /// <returns>64 lower-case hex characters.</returns> |
| | | 21 | | /// <exception cref="ArgumentNullException"><paramref name="files"/> is <see langword="null"/>.</exception> |
| | | 22 | | public static string Compute( IEnumerable<KeyValuePair<string, string>> files ) |
| | | 23 | | { |
| | 832 | 24 | | ArgumentNullException.ThrowIfNull( files ); |
| | | 25 | | |
| | 832 | 26 | | using var hash = IncrementalHash.CreateHash( HashAlgorithmName.SHA256 ); |
| | | 27 | | |
| | | 28 | | |
| | 7584 | 29 | | foreach ( var (name, text) in files.OrderBy( f => f.Key == ManifestFile ? 0 : 1 ).ThenBy( f => f.Key, StringComp |
| | | 30 | | { |
| | 2960 | 31 | | hash.AppendData( Encoding.UTF8.GetBytes( name + "\n" ) ); |
| | 2960 | 32 | | hash.AppendData( Encoding.UTF8.GetBytes( Normalize( text ) + "\n" ) ); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | |
| | 832 | 36 | | return Convert.ToHexString( hash.GetHashAndReset() ).ToLowerInvariant(); |
| | 832 | 37 | | } |
| | | 38 | | |
| | | 39 | | /// <summary>Removes a leading BOM and turns CRLF / CR into LF.</summary> |
| | | 40 | | /// <param name="text">The file text.</param> |
| | | 41 | | /// <returns>The normalised text.</returns> |
| | 6089 | 42 | | internal static string Normalize( string text ) => text.TrimStart( '' ).Replace( "\r\n", "\n", StringComparison.Ord |
| | | 43 | | } |