Skip to content

Commit

Permalink
Enable rule CA1869 - Cache and reuse 'JsonSerializerOptions' (#90895)
Browse files Browse the repository at this point in the history
* Enable rule CA1869

* Fix ocurrences in src/tasks projects

* Fix more occurrences on installer and mono\wasm
  • Loading branch information
jozkee committed Sep 11, 2023
1 parent 9d08b24 commit 6504cdb
Show file tree
Hide file tree
Showing 10 changed files with 54 additions and 42 deletions.
3 changes: 3 additions & 0 deletions eng/CodeAnalysis.src.globalconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions eng/CodeAnalysis.test.globalconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -65,7 +67,7 @@ public static void Create(MetadataReader metadataReader, string clsidMapPath)

using (StreamWriter writer = File.CreateText(clsidMapPath))
{
writer.Write(JsonSerializer.Serialize(clsidMap, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }));
writer.Write(JsonSerializer.Serialize(clsidMap, s_jsonOptions));
}
}

Expand Down
14 changes: 8 additions & 6 deletions src/mono/wasm/host/CommonConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -62,12 +69,7 @@ private CommonConfiguration(string[] args)

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}");

Expand Down
12 changes: 7 additions & 5 deletions src/mono/wasm/host/RunArgumentsJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
7 changes: 1 addition & 6 deletions src/mono/wasm/host/RunConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,7 @@ public RunConfiguration(string runtimeConfigPath, string? hostArg)

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}");

Expand Down
5 changes: 3 additions & 2 deletions src/tasks/Common/FileCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand All @@ -34,7 +35,7 @@ public FileCache(string? cacheFilePath, TaskLoggingHelper log)
{
_oldCache = (CompilerCache?)JsonSerializer.Deserialize(File.ReadAllText(cacheFilePath),
typeof(CompilerCache),
new JsonSerializerOptions());
s_jsonOptions);
}

_oldCache ??= new();
Expand Down Expand Up @@ -84,7 +85,7 @@ public bool Save(string? cacheFilePath)
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -72,17 +82,8 @@ private bool TryConvertInputToDictionary(string inputFilePath, [NotNullWhen(true
{
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)
{
Expand Down
16 changes: 9 additions & 7 deletions src/tasks/WasmAppBuilder/WasmAppBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
//
Expand Down Expand Up @@ -368,13 +376,7 @@ protected override bool ExecuteInternal()
{
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);
}

Expand Down
11 changes: 6 additions & 5 deletions src/tasks/WorkloadBuildTasks/InstallWorkloadFromArtifacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ public partial class InstallWorkloadFromArtifacts : Task
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();
Expand Down Expand Up @@ -330,11 +335,7 @@ private bool InstallWorkloadManifest(ITaskItem workloadId, string name, string v
{
manifest = JsonSerializer.Deserialize<ManifestInformation>(
File.ReadAllBytes(jsonPath),
new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
});
s_jsonOptions);

if (manifest == null)
{
Expand Down

0 comments on commit 6504cdb

Please sign in to comment.