Enable Net 7 and Net 8 style rules.

This commit is contained in:
RoosterDragon
2024-11-25 20:15:58 +00:00
committed by Gustas Kažukauskas
parent 71ae0aedfb
commit cfde11556f
31 changed files with 74 additions and 94 deletions

View File

@@ -748,7 +748,7 @@ dotnet_diagnostic.CA1305.severity = warning
dotnet_diagnostic.CA1310.severity = warning
# Specify a culture or use an invariant version.
dotnet_diagnostic.CA1311.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1311.severity = warning
### Portability and Interoperability Rules
### https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/interoperability-warnings
@@ -763,19 +763,19 @@ dotnet_diagnostic.CA1417.severity = warning
dotnet_diagnostic.CA1507.severity = warning
# Use ArgumentNullException throw helper.
dotnet_diagnostic.CA1510.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1510.severity = warning
# Use ArgumentException throw helper.
dotnet_diagnostic.CA1511.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1511.severity = warning
# Use ArgumentOutOfRangeException throw helper.
dotnet_diagnostic.CA1512.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1512.severity = warning
# Use ObjectDisposedException throw helper.
dotnet_diagnostic.CA1513.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1513.severity = warning
# Avoid redundant length argument.
dotnet_diagnostic.CA1514.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1514.severity = warning
### Naming Rules
### https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/naming-warnings
@@ -868,8 +868,8 @@ dotnet_diagnostic.CA1843.severity = warning
# Provide memory-based overrides of async methods when subclassing 'Stream'.
dotnet_diagnostic.CA1844.severity = warning
# Use span-based 'string.Concat'. (Not available on mono)
dotnet_diagnostic.CA1845.severity = none
# Use span-based 'string.Concat'.
dotnet_diagnostic.CA1845.severity = warning
# Prefer AsSpan over Substring.
dotnet_diagnostic.CA1846.severity = warning
@@ -878,34 +878,34 @@ dotnet_diagnostic.CA1846.severity = warning
dotnet_diagnostic.CA1847.severity = warning
# Call async methods when in an async method.
dotnet_diagnostic.CA1849.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1849.severity = warning
# Prefer static HashData method over ComputeHash. (Not available on mono)
dotnet_diagnostic.CA1850.severity = none # TODO: Change to warning once using .NET 7 or later AND once supported by mono.
# Prefer static HashData method over ComputeHash.
dotnet_diagnostic.CA1850.severity = warning
# Possible multiple enumerations of IEnumerable collection.
#dotnet_code_quality.CA1851.enumeration_methods =
dotnet_code_quality.CA1851.linq_chain_methods = M:OpenRA.Traits.IRenderModifier.Modify*
dotnet_code_quality.CA1851.assume_method_enumerates_parameters = true
dotnet_diagnostic.CA1851.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1851.severity = warning
# Seal internal types.
dotnet_diagnostic.CA1852.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1852.severity = warning
# Unnecessary call to 'Dictionary.ContainsKey(key)'.
dotnet_diagnostic.CA1853.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1853.severity = warning
# Prefer the IDictionary.TryGetValue(TKey, out TValue) method.
dotnet_diagnostic.CA1854.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1854.severity = warning
# Use Span<T>.Clear() instead of Span<T>.Fill().
dotnet_diagnostic.CA1855.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1855.severity = warning
# Incorrect usage of ConstantExpected attribute.
dotnet_diagnostic.CA1856.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1856.severity = warning
# The parameter expects a constant for optimal performance.
dotnet_diagnostic.CA1857.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1857.severity = warning
# Use StartsWith instead of IndexOf.
dotnet_diagnostic.CA1858.severity = warning
@@ -917,24 +917,24 @@ dotnet_diagnostic.CA1860.severity = warning
dotnet_diagnostic.CA1862.severity = warning
# Use 'CompositeFormat'.
dotnet_diagnostic.CA1863.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA1863.severity = warning
# Prefer the 'IDictionary.TryAdd(TKey, TValue)' method.
dotnet_diagnostic.CA1864.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1864.severity = warning
# Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char.
dotnet_diagnostic.CA1865.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1866.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1867.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1865.severity = warning
dotnet_diagnostic.CA1866.severity = warning
dotnet_diagnostic.CA1867.severity = warning
# Unnecessary call to 'Contains' for sets.
dotnet_diagnostic.CA1868.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1868.severity = warning
# Cache and reuse 'JsonSerializerOptions' instances.
dotnet_diagnostic.CA1869.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1869.severity = warning
# Use a cached 'SearchValues' instance.
dotnet_diagnostic.CA1870.severity = suggestion # TODO: Change to warning once using .NET 8 or later.
dotnet_diagnostic.CA1870.severity = warning
# Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull'.
dotnet_diagnostic.CA1871.severity = warning
@@ -964,7 +964,7 @@ dotnet_diagnostic.CA2016.severity = warning
dotnet_diagnostic.CA2018.severity = warning
# ThreadStatic fields should not use inline initialization.
dotnet_diagnostic.CA2019.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA2019.severity = warning
# Don't call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types.
dotnet_diagnostic.CA2021.severity = warning
@@ -1041,10 +1041,10 @@ dotnet_diagnostic.CA2250.severity = warning
dotnet_diagnostic.CA2251.severity = warning
# Ensure ThreadStatic is only used with static fields.
dotnet_diagnostic.CA2259.severity = suggestion # TODO: Change to warning once using .NET 7 or later.
dotnet_diagnostic.CA2259.severity = warning
# Prefer generic overload when type is known.
dotnet_diagnostic.CA2263.severity = none # TODO: Change to warning once mono is dropped.
dotnet_diagnostic.CA2263.severity = warning
# Do not pass a non-nullable value to 'ArgumentNullException.ThrowIfNull'.
dotnet_diagnostic.CA2264.severity = warning

View File

@@ -210,8 +210,7 @@ namespace OpenRA
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(parameters);
using (var csp = SHA1.Create())
return Convert.ToBase64String(rsa.SignHash(csp.ComputeHash(data), CryptoConfig.MapNameToOID("SHA1")));
return Convert.ToBase64String(rsa.SignHash(SHA1.HashData(data), CryptoConfig.MapNameToOID("SHA1")));
}
}
catch (Exception e)
@@ -236,8 +235,7 @@ namespace OpenRA
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(parameters);
using (var csp = SHA1.Create())
return rsa.VerifyHash(csp.ComputeHash(data), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(signature));
return rsa.VerifyHash(SHA1.HashData(data), CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(signature));
}
}
catch (Exception e)
@@ -252,14 +250,12 @@ namespace OpenRA
public static string SHA1Hash(Stream data)
{
using var csp = SHA1.Create();
return ToHex(csp.ComputeHash(data), true);
return ToHex(SHA1.HashData(data), true);
}
public static string SHA1Hash(byte[] data)
{
using var csp = SHA1.Create();
return ToHex(csp.ComputeHash(data), true);
return ToHex(SHA1.HashData(data), true);
}
public static string SHA1Hash(string data)

View File

@@ -27,8 +27,7 @@ namespace OpenRA.FileFormats
public ReplayMetadata(GameInformation info)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
ArgumentNullException.ThrowIfNull(info);
GameInfo = info;
}

View File

@@ -111,8 +111,7 @@ namespace OpenRA
public bool TryGetMessage(string key, out string value, object[] args = null)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
ArgumentNullException.ThrowIfNull(key);
try
{

View File

@@ -100,11 +100,9 @@ namespace OpenRA
/// <summary>Adds the player information at start-up.</summary>
public void AddPlayer(OpenRA.Player runtimePlayer, Session lobbyInfo)
{
if (runtimePlayer == null)
throw new ArgumentNullException(nameof(runtimePlayer));
ArgumentNullException.ThrowIfNull(runtimePlayer);
if (lobbyInfo == null)
throw new ArgumentNullException(nameof(lobbyInfo));
ArgumentNullException.ThrowIfNull(lobbyInfo);
// We don't care about spectators and map players
if (runtimePlayer.NonCombatant || !runtimePlayer.Playable)

View File

@@ -31,9 +31,9 @@ namespace OpenRA.Graphics
public interface IModelWidget
{
public string Palette { get; }
public float Scale { get; }
public void Setup(Func<bool> isVisible, Func<string> getPalette, Func<string> getPlayerPalette,
string Palette { get; }
float Scale { get; }
void Setup(Func<bool> isVisible, Func<string> getPalette, Func<string> getPlayerPalette,
Func<float> getScale, Func<IModel> getVoxel, Func<WRot> getRotation);
}

View File

@@ -23,8 +23,7 @@ namespace OpenRA.Primitives
public void Add(Action a, long desiredTime)
{
if (a == null)
throw new ArgumentNullException(nameof(a));
ArgumentNullException.ThrowIfNull(a);
lock (actions)
{

View File

@@ -21,8 +21,7 @@ namespace OpenRA
public ActorInfoDictionary(IReadOnlyDictionary<string, ActorInfo> dict)
{
if (dict == null)
throw new ArgumentNullException(nameof(dict));
ArgumentNullException.ThrowIfNull(dict);
this.dict = new Dictionary<string, ActorInfo>(dict);
}

View File

@@ -21,8 +21,7 @@ namespace OpenRA.Primitives
public Cache(Func<T, U> loader, IEqualityComparer<T> c)
{
if (loader == null)
throw new ArgumentNullException(nameof(loader));
ArgumentNullException.ThrowIfNull(loader);
this.loader = loader;
cache = new Dictionary<T, U>(c);

View File

@@ -22,8 +22,7 @@ namespace OpenRA.Primitives
public ConcurrentCache(Func<T, U> loader, IEqualityComparer<T> c)
{
if (loader == null)
throw new ArgumentNullException(nameof(loader));
ArgumentNullException.ThrowIfNull(loader);
this.loader = loader;
cache = new ConcurrentDictionary<T, U>(c);

View File

@@ -27,8 +27,7 @@ namespace OpenRA.Primitives
protected ReadOnlyAdapterStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
ArgumentNullException.ThrowIfNull(stream);
if (!stream.CanRead)
throw new ArgumentException("stream must be readable.", nameof(stream));

View File

@@ -65,8 +65,7 @@ namespace OpenRA.Primitives
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
ArgumentNullException.ThrowIfNull(array);
if (arrayIndex < 0)
throw new ArgumentNullException(nameof(arrayIndex));

View File

@@ -32,8 +32,7 @@ namespace OpenRA.Primitives
/// <param name="count">The length of the segment.</param>
public SegmentStream(Stream stream, long offset, long count)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
ArgumentNullException.ThrowIfNull(stream);
if (!stream.CanSeek)
throw new ArgumentException("stream must be seekable.", nameof(stream));
if (offset < 0)

View File

@@ -150,7 +150,7 @@ namespace OpenRA.Scripting
// Remove the namespace and the trailing "Info"
return types.SelectMany(i => i.GetGenericArguments())
.Select(g => g.Name.Split('.', StringSplitOptions.RemoveEmptyEntries).LastOrDefault())
.Select(s => s.EndsWith("Info", StringComparison.Ordinal) ? s.Remove(s.Length - 4, 4) : s)
.Select(s => s.EndsWith("Info", StringComparison.Ordinal) ? s[..^4] : s)
.ToArray();
}
}

View File

@@ -359,8 +359,7 @@ namespace OpenRA
public bool PlayPredefined(SoundType soundType, Ruleset ruleset, Player player, Actor voicedActor, string type, string definition, string variant,
bool relative, WPos pos, float volumeModifier, bool attenuateVolume)
{
if (ruleset == null)
throw new ArgumentNullException(nameof(ruleset));
ArgumentNullException.ThrowIfNull(ruleset);
if (definition == null || DisableAllSounds || (DisableWorldSounds && soundType == SoundType.World))
return false;
@@ -460,8 +459,7 @@ namespace OpenRA
public bool PlayNotification(Ruleset rules, Player player, string type, string notification, string variant)
{
if (rules == null)
throw new ArgumentNullException(nameof(rules));
ArgumentNullException.ThrowIfNull(rules);
if (type == null || notification == null)
return false;

View File

@@ -75,7 +75,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders
{
enum Format : ushort { XORPrev = 0x20, XORLCW = 0x40, LCW = 0x80 }
class TrimmedFrame : ISpriteFrame
sealed class TrimmedFrame : ISpriteFrame
{
public SpriteFrameType Type => SpriteFrameType.Indexed8;
public Size Size { get; }

View File

@@ -96,7 +96,7 @@ namespace OpenRA.Mods.Common.Widgets
}
}
class PaintMarkerTileEditorAction : IEditorAction
sealed class PaintMarkerTileEditorAction : IEditorAction
{
[FluentReference("amount", "type")]
const string AddedMarkerTiles = "notification-added-marker-tiles";
@@ -156,7 +156,7 @@ namespace OpenRA.Mods.Common.Widgets
}
}
class ClearSelectedMarkerTilesEditorAction : IEditorAction
sealed class ClearSelectedMarkerTilesEditorAction : IEditorAction
{
[FluentReference("amount", "type")]
const string ClearedSelectedMarkerTiles = "notification-cleared-selected-marker-tiles";
@@ -195,7 +195,7 @@ namespace OpenRA.Mods.Common.Widgets
}
}
class ClearAllMarkerTilesEditorAction : IEditorAction
sealed class ClearAllMarkerTilesEditorAction : IEditorAction
{
[FluentReference("amount")]
const string ClearedAllMarkerTiles = "notification-cleared-all-marker-tiles";
@@ -211,7 +211,7 @@ namespace OpenRA.Mods.Common.Widgets
this.markerLayerOverlay = markerLayerOverlay;
tiles = new Dictionary<int, HashSet<CPos>>(markerLayerOverlay.Tiles);
var allTilesCount = tiles.Values.Select(x => x.Count).Sum();
var allTilesCount = tiles.Values.Sum(x => x.Count);
Text = FluentProvider.GetMessage(ClearedAllMarkerTiles, "amount", allTilesCount);
}

View File

@@ -58,7 +58,7 @@ namespace OpenRA.Mods.Common.FileFormats
var audioFormat = s.ReadInt16();
audioType = (WaveType)audioFormat;
if (!Enum.IsDefined(typeof(WaveType), audioType))
if (!Enum.IsDefined(audioType))
throw new NotSupportedException($"Compression type {audioFormat} is not supported.");
channels = s.ReadInt16();

View File

@@ -17,7 +17,7 @@ namespace OpenRA.Mods.Common.FileSystem
[RequireExplicitImplementation]
public interface IFileSystemExternalContent
{
public bool InstallContentIfRequired(ModData modData);
bool InstallContentIfRequired(ModData modData);
}
public class DefaultFileSystemLoader : IFileSystemLoader

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Mods.Common
{
public class ItchIntegration : IGlobalModData
{
class User
sealed class User
{
[JsonProperty("url")]
public string Url { get; set; }
@@ -43,7 +43,7 @@ namespace OpenRA.Mods.Common
public string DisplayName { get; set; }
}
class Root
sealed class Root
{
public User User { get; set; }
}

View File

@@ -502,7 +502,7 @@ namespace OpenRA.Mods.Common.Lint
}
}
class Keys
sealed class Keys
{
readonly HashSet<string> keys = new();
readonly List<(string Key, string Context)> keysWithContext = new();

View File

@@ -59,7 +59,7 @@ namespace OpenRA.Mods.Common.Lint
{
// Remove the "Info" suffix.
var traitName = traitInfo.GetType().Name;
traitName = traitName.Remove(traitName.Length - 4);
traitName = traitName[..^4];
var fields = Utility.GetFields(traitInfo.GetType());
foreach (var field in fields)

View File

@@ -31,7 +31,7 @@ namespace OpenRA.Mods.Common.Lint
{
// Remove the "Info" suffix.
var traitName = traitInfo.GetType().Name;
traitName = traitName.Remove(traitName.Length - 4);
traitName = traitName[..^4];
var locations = traitLocation.SystemActors.ToString().Replace(", ", " or ");
emitError($"`{traitName}` does not belong on `{actorInfo.Key}`. It is a system trait meant for {locations}.");
}

View File

@@ -567,7 +567,7 @@ namespace OpenRA.Mods.Common.Scripting
"so you must not add new triggers at the same time that you are calling this function.")]
public void Clear(Actor actor, string triggerName)
{
var trigger = (Trigger)Enum.Parse(typeof(Trigger), triggerName);
var trigger = Enum.Parse<Trigger>(triggerName);
if (actor == null)
throw new NullReferenceException(nameof(actor));

View File

@@ -47,7 +47,7 @@ namespace OpenRA.Mods.Common.Scripting
public event Action<Actor, Actor> OnProducedInternal = (a, b) => { };
public event Action<Actor, Actor> OnOtherProducedInternal = (a, b) => { };
readonly List<Triggerable>[] triggerables = Exts.MakeArray(Enum.GetValues(typeof(Trigger)).Length, _ => new List<Triggerable>());
readonly List<Triggerable>[] triggerables = Exts.MakeArray(Enum.GetValues<Trigger>().Length, _ => new List<Triggerable>());
readonly struct Triggerable : IDisposable
{
@@ -526,7 +526,7 @@ namespace OpenRA.Mods.Common.Scripting
public void ClearAll()
{
foreach (Trigger t in Enum.GetValues(typeof(Trigger)))
foreach (var t in Enum.GetValues<Trigger>())
Clear(t);
}

View File

@@ -22,7 +22,7 @@ namespace OpenRA.Mods.Common.Server
{
public class SkirmishLogic : ServerTrait, IClientJoined, INotifySyncLobbyInfo
{
class SkirmishSlot
sealed class SkirmishSlot
{
[FieldLoader.Serialize(FromYamlKey = true)]
public readonly string Slot;

View File

@@ -91,7 +91,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var visOptionTemplate = visibilityPanel.Get<CheckboxWidget>("VISIBILITY_TEMPLATE");
visibilityPanel.RemoveChildren();
foreach (MapVisibility visibilityOption in Enum.GetValues(typeof(MapVisibility)))
foreach (var visibilityOption in Enum.GetValues<MapVisibility>())
{
// To prevent users from breaking the game only show the 'Shellmap' option when it is already set.
if (visibilityOption == MapVisibility.Shellmap && !map.Visibility.HasFlag(visibilityOption))
@@ -311,8 +311,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
try
{
if (package == null)
throw new ArgumentNullException(nameof(package));
ArgumentNullException.ThrowIfNull(package);
map.Save(package);

View File

@@ -102,7 +102,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
this.worldRenderer = worldRenderer;
MiniYaml yaml;
var keyNames = Enum.GetNames(typeof(ObserverStatsPanel));
var keyNames = Enum.GetNames<ObserverStatsPanel>();
var statsHotkeys = new HotkeyReference[keyNames.Length];
for (var i = 0; i < keyNames.Length; i++)
statsHotkeys[i] = logicArgs.TryGetValue("Statistics" + keyNames[i] + "Key", out yaml) ? modData.Hotkeys[yaml.Value] : new HotkeyReference();

View File

@@ -321,7 +321,7 @@ namespace OpenRA.Mods.Common.Widgets
if (e.Modifiers.HasModifier(Modifiers.Ctrl) && CursorPosition < Text.Length)
{
// Write directly to the Text backing field to avoid unnecessary validation
text = text.Remove(CursorPosition);
text = text[..CursorPosition];
CursorPosition = CursorPosition.Clamp(0, text.Length);
OnTextEdited();
@@ -379,7 +379,7 @@ namespace OpenRA.Mods.Common.Widgets
if ((!isOSX && e.Modifiers.HasModifier(Modifiers.Ctrl)) || (isOSX && e.Modifiers.HasModifier(Modifiers.Alt)))
text = text[..CursorPosition] + text[GetNextWhitespaceIndex()..];
else if (isOSX && e.Modifiers.HasModifier(Modifiers.Meta))
text = text.Remove(CursorPosition);
text = text[..CursorPosition];
else
text = text.Remove(CursorPosition, 1);

View File

@@ -10,7 +10,6 @@
#endregion
using System;
using System.Linq;
using NUnit.Framework;
namespace OpenRA.Test
@@ -21,7 +20,7 @@ namespace OpenRA.Test
[TestCase(TestName = "Test CPos and MPos conversion and back again.")]
public void CoarseToMapProjection()
{
foreach (var gridType in Enum.GetValues(typeof(MapGridType)).Cast<MapGridType>())
foreach (var gridType in Enum.GetValues<MapGridType>())
{
for (var x = 0; x < 12; x++)
{

View File

@@ -44,9 +44,8 @@ namespace OpenRA.Test
void AssertParseFailure(string expression, string errorMessage)
{
var actualErrorMessage = Assert.Throws(typeof(InvalidDataException),
() => new IntegerExpression(expression).Evaluate(testValues),
expression).Message;
var actualErrorMessage = Assert.Throws<InvalidDataException>(
() => new IntegerExpression(expression).Evaluate(testValues), expression).Message;
Assert.That(errorMessage, Is.EqualTo(actualErrorMessage), expression + " ===> " + actualErrorMessage);
}