Enable rule CA1869 - Cache and reuse 'JsonSerializerOptions' (#90895)

* Enable rule CA1869

* Fix ocurrences in src/tasks projects

* Fix more occurrences on installer and mono\wasm
This commit is contained in:
David Cantú 2023-09-11 12:53:49 -05:00 committed by GitHub
parent 9d08b24d74
commit 6504cdb355
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 54 additions and 42 deletions

View File

@ -486,6 +486,9 @@ dotnet_diagnostic.CA1864.severity = warning
# CA1868: Unnecessary call to 'Contains' for sets
dotnet_diagnostic.CA1868.severity = warning
# CA1869: Cache and reuse 'JsonSerializerOptions' instances
dotnet_diagnostic.CA1869.severity = warning
# CA2000: Dispose objects before losing scope
dotnet_diagnostic.CA2000.severity = none

View File

@ -483,6 +483,9 @@ dotnet_diagnostic.CA1864.severity = none
# CA1868: Unnecessary call to 'Contains' for sets
dotnet_diagnostic.CA1868.severity = none
# CA1869: Cache and reuse 'JsonSerializerOptions' instances
dotnet_diagnostic.CA1869.severity = none
# CA2000: Dispose objects before losing scope
dotnet_diagnostic.CA2000.severity = none

View File

@ -18,6 +18,8 @@ namespace Microsoft.NET.HostModel.ComHost
{
public static class ClsidMap
{
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };
private struct ClsidEntry
{
[JsonPropertyName("type")]
@ -65,7 +67,7 @@ namespace Microsoft.NET.HostModel.ComHost
using (StreamWriter writer = File.CreateText(clsidMapPath))
{
writer.Write(JsonSerializer.Serialize(clsidMap, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }));
writer.Write(JsonSerializer.Serialize(clsidMap, s_jsonOptions));
}
}

View File

@ -26,7 +26,14 @@ internal sealed class CommonConfiguration
public string? RuntimeConfigPath { get; private set; }
private string? hostArg;
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
PropertyNameCaseInsensitive = true
};
public static JsonSerializerOptions JsonOptions => s_jsonOptions;
public static CommonConfiguration FromCommandLineArguments(string[] args) => new CommonConfiguration(args);
private CommonConfiguration(string[] args)
@ -62,12 +69,7 @@ internal sealed class CommonConfiguration
RuntimeConfig? rconfig = JsonSerializer.Deserialize<RuntimeConfig>(
File.ReadAllText(RuntimeConfigPath),
new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
PropertyNameCaseInsensitive = true
});
JsonOptions);
if (rconfig == null)
throw new CommandLineException($"Failed to deserialize {RuntimeConfigPath}");

View File

@ -18,17 +18,19 @@ internal sealed record RunArgumentsJson(
bool debugging = false
)
{
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
// using an explicit property because the deserializer doesn't like
// extension data in the record constructor
[property: JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
public void Save(string file)
{
string json = JsonSerializer.Serialize(this, new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
string json = JsonSerializer.Serialize(this, s_jsonOptions);
File.WriteAllText(file, json);
}
}

View File

@ -27,12 +27,7 @@ internal sealed class RunConfiguration
RuntimeConfig? rconfig = JsonSerializer.Deserialize<RuntimeConfig>(
File.ReadAllText(runtimeConfigPath),
new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
PropertyNameCaseInsensitive = true
});
CommonConfiguration.JsonOptions);
if (rconfig == null)
throw new Exception($"Failed to deserialize {runtimeConfigPath}");

View File

@ -16,6 +16,7 @@ internal sealed class FileCache
{
private CompilerCache? _newCache;
private CompilerCache? _oldCache;
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions { WriteIndented = true };
public bool Enabled { get; }
public TaskLoggingHelper Log { get; }
@ -34,7 +35,7 @@ internal sealed class FileCache
{
_oldCache = (CompilerCache?)JsonSerializer.Deserialize(File.ReadAllText(cacheFilePath),
typeof(CompilerCache),
new JsonSerializerOptions());
s_jsonOptions);
}
_oldCache ??= new();
@ -84,7 +85,7 @@ internal sealed class FileCache
if (!Enabled || string.IsNullOrEmpty(cacheFilePath))
return false;
var json = JsonSerializer.Serialize (_newCache, new JsonSerializerOptions { WriteIndented = true });
var json = JsonSerializer.Serialize (_newCache, s_jsonOptions);
File.WriteAllText(cacheFilePath!, json);
return true;
}

View File

@ -30,6 +30,16 @@ public class RuntimeConfigParserTask : Task
/// </summary>
public ITaskItem[] RuntimeConfigReservedProperties { get; set; } = Array.Empty<ITaskItem>();
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
Converters =
{
new StringConverter()
}
};
public override bool Execute()
{
if (string.IsNullOrEmpty(RuntimeConfigFile))
@ -72,17 +82,8 @@ public class RuntimeConfigParserTask : Task
{
result = null;
var options = new JsonSerializerOptions {
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
Converters =
{
new StringConverter()
}
};
var jsonString = File.ReadAllText(inputFilePath);
var parsedJson = JsonSerializer.Deserialize<Root>(jsonString, options);
var parsedJson = JsonSerializer.Deserialize<Root>(jsonString, s_jsonOptions);
if (parsedJson == null)
{

View File

@ -29,6 +29,14 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
public string? RuntimeAssetsLocation { get; set; }
public bool CacheBootResources { get; set; }
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true
};
// <summary>
// Extra json elements to add to _framework/blazor.boot.json
//
@ -368,13 +376,7 @@ public class WasmAppBuilder : WasmAppBuilderBaseTask
{
helper.ComputeResourcesHash(bootConfig);
var jsonOptions = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true
};
var json = JsonSerializer.Serialize(bootConfig, jsonOptions);
var json = JsonSerializer.Serialize(bootConfig, s_jsonOptions);
sw.Write(json);
}

View File

@ -49,6 +49,11 @@ namespace Microsoft.Workload.Build.Tasks
private string AllManifestsStampPath => Path.Combine(SdkWithNoWorkloadInstalledPath, ".all-manifests.stamp");
private string _tempDir = string.Empty;
private string _nugetCachePath = string.Empty;
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
[GeneratedRegex(@"^\d+\.\d+\.\d+(-[A-z]*\.*\d*)?")]
private static partial Regex bandVersionRegex();
@ -330,11 +335,7 @@ namespace Microsoft.Workload.Build.Tasks
{
manifest = JsonSerializer.Deserialize<ManifestInformation>(
File.ReadAllBytes(jsonPath),
new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
});
s_jsonOptions);
if (manifest == null)
{