|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.IO; |
| 6 | +using System.Security.Cryptography; |
| 7 | +using System.Text.Json; |
| 8 | +using System.Text.Json.Serialization.Metadata; |
| 9 | +using Microsoft.Build.Framework; |
| 10 | +using Microsoft.Build.Utilities; |
| 11 | + |
| 12 | +namespace Microsoft.NET.Sdk.WebAssembly; |
| 13 | + |
| 14 | +public static class ArtifactWriter |
| 15 | +{ |
| 16 | + public static bool PersistFileIfChanged<T>(TaskLoggingHelper log, T manifest, string artifactPath, JsonTypeInfo<T> serializer) |
| 17 | + { |
| 18 | + var data = JsonSerializer.SerializeToUtf8Bytes(manifest, serializer); |
| 19 | + return PersistFileIfChanged(log, data, artifactPath); |
| 20 | + } |
| 21 | + |
| 22 | + public static bool PersistFileIfChanged(TaskLoggingHelper log, byte[] data, string artifactPath) |
| 23 | + { |
| 24 | + var newHash = ComputeHash(data); |
| 25 | + var fileExists = File.Exists(artifactPath); |
| 26 | + var existingManifestHash = fileExists ? ComputeHash(artifactPath) : null; |
| 27 | + |
| 28 | + if (!fileExists) |
| 29 | + { |
| 30 | + log.LogMessage(MessageImportance.Low, $"Creating artifact because artifact file '{artifactPath}' does not exist."); |
| 31 | + File.WriteAllBytes(artifactPath, data); |
| 32 | + return true; |
| 33 | + } |
| 34 | + else if (!string.Equals(newHash, existingManifestHash, StringComparison.Ordinal)) |
| 35 | + { |
| 36 | + log.LogMessage(MessageImportance.Low, $"Updating artifact because artifact version '{newHash}' is different from existing artifact hash '{existingManifestHash}'."); |
| 37 | + File.WriteAllBytes(artifactPath, data); |
| 38 | + return true; |
| 39 | + } |
| 40 | + else |
| 41 | + { |
| 42 | + log.LogMessage(MessageImportance.Low, $"Skipping artifact updated because artifact version '{existingManifestHash}' has not changed."); |
| 43 | + return false; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static string ComputeHash(string artifactPath) => ComputeHash(File.ReadAllBytes(artifactPath)); |
| 48 | + |
| 49 | + private static string ComputeHash(byte[] data) |
| 50 | + { |
| 51 | +#if NET6_0_OR_GREATER |
| 52 | + var hash = SHA256.HashData(data); |
| 53 | + return Convert.ToBase64String(hash); |
| 54 | +#else |
| 55 | + using var sha256 = SHA256.Create(); |
| 56 | + return Convert.ToBase64String(sha256.ComputeHash(data)); |
| 57 | +#endif |
| 58 | + } |
| 59 | +} |
0 commit comments