Skip to content

Commit a233d38

Browse files
authored
Improve code consistency from SonarCloud hints (#365)
* Fix SonarCloud code consistency hints * Add timeout to RegEx * Remove an unused variable
1 parent a995ac4 commit a233d38

14 files changed

Lines changed: 39 additions & 46 deletions

File tree

src/SmartFormat.Extensions.Time/TimeFormatter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ private TimeTextInfo GetTimeTextInfo(IFormattingInfo formattingInfo, bool v2Comp
203203

204204
if (timeTextInfoFromCulture != null) return timeTextInfoFromCulture;
205205

206-
if(timeTextInfoFromCulture is null && FallbackLanguage == string.Empty)
206+
if(FallbackLanguage == string.Empty)
207207
throw new FormattingException(formattingInfo.Placeholder, $"{nameof(TimeTextInfo)} could not be found for the given culture argument '{formattingInfo.FormatterOptions}'.", 0);
208208

209209
if(FallbackLanguage != string.Empty)
@@ -232,4 +232,4 @@ private static CultureInfo GetCultureInfo(IFormattingInfo formattingInfo, bool v
232232

233233
return cultureInfo;
234234
}
235-
}
235+
}

src/SmartFormat.Extensions.Time/Utilities/TimeSpanFormatOptionsConverter.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Copyright SmartFormat Project maintainers and contributors.
33
// Licensed under the MIT license.
44

5+
using System;
56
using System.Collections.Generic;
67
using System.Text.RegularExpressions;
78

@@ -10,9 +11,8 @@ namespace SmartFormat.Extensions.Time.Utilities;
1011
internal static class TimeSpanFormatOptionsConverter
1112
{
1213
private static readonly Regex parser =
13-
new Regex(
14-
@"\b(w|week|weeks|d|day|days|h|hour|hours|m|minute|minutes|s|second|seconds|ms|millisecond|milliseconds|auto|short|fill|full|abbr|noabbr|less|noless)\b",
15-
RegexOptions.Compiled | RegexOptions.IgnoreCase);
14+
new(@"\b(w|week|weeks|d|day|days|h|hour|hours|m|minute|minutes|s|second|seconds|ms|millisecond|milliseconds|auto|short|fill|full|abbr|noabbr|less|noless)\b",
15+
RegexOptions.Compiled | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(500));
1616

1717
public static TimeSpanFormatOptions Merge(this TimeSpanFormatOptions left, TimeSpanFormatOptions right)
1818
{
@@ -117,4 +117,4 @@ public static TimeSpanFormatOptions Parse(string formatString)
117117

118118
return t;
119119
}
120-
}
120+
}

src/SmartFormat.Extensions.Xml/XmlSource.cs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,19 @@ public class XmlSource : Source
1717
/// <inheritdoc />
1818
public override bool TryEvaluateSelector(ISelectorInfo selectorInfo)
1919
{
20-
if (selectorInfo.CurrentValue is XElement element)
21-
{
22-
var selector = selectorInfo.SelectorText;
23-
// Find elements that match a selector
24-
var selectorMatchedElements =
25-
element.Elements()
26-
.Where(x => x.Name.LocalName == selector)
27-
.ToList();
28-
if (selectorMatchedElements.Any())
29-
{
30-
selectorInfo.Result = selectorMatchedElements;
31-
return true;
32-
}
33-
}
20+
if (selectorInfo.CurrentValue is not XElement element) return false;
21+
22+
var selector = selectorInfo.SelectorText;
23+
// Find elements that match a selector
24+
var selectorMatchedElements =
25+
element.Elements()
26+
.Where(x => x.Name.LocalName == selector)
27+
.ToList();
28+
29+
if (selectorMatchedElements.Count == 0) return false;
30+
31+
selectorInfo.Result = selectorMatchedElements;
32+
return true;
3433

35-
return false;
3634
}
37-
}
35+
}

src/SmartFormat.Tests/Core/FormatterExtensionsTests.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ public void Add_Known_FormatterExtensions_In_Recommended_Order()
8383

8484
#region: Default Extensions :
8585

86-
#pragma warning disable CA1861 // Not called repeatedly, but called with different arguments
8786
[TestCase("{0:cond:zero|one|two}", 0, "zero")]
8887
[TestCase("{0:cond:zero|one|two}", 1, "one")]
8988
[TestCase("{0:cond:zero|one|two}", 2, "two")]
@@ -97,7 +96,6 @@ public void Invoke_extensions_by_name(string format, object arg0, string expecte
9796
var actualResult = smart.Format(new CultureInfo("en-US"), format, arg0); // must be culture with decimal point
9897
Assert.That(actualResult, Is.EqualTo(expectedResult));
9998
}
100-
#pragma warning restore CA1861
10199

102100
#endregion
103101

src/SmartFormat.Tests/Core/SettingsTests.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,8 @@ public void TryingToAddDisallowedSelectorCharacters_Should_Throw()
1919
public void ExistingSelectorCharacter_Should_Not_Be_Added()
2020
{
2121
var settings = new SmartSettings();
22-
#pragma warning disable CA1861 // Not called repeatedly
2322
settings.Parser.AddCustomSelectorChars(new[] {'A', ' '});
2423
settings.Parser.AddCustomSelectorChars(new[] {' '});
25-
#pragma warning restore CA1861
2624
Assert.Multiple(() =>
2725
{
2826
Assert.That(settings.Parser.CustomSelectorChars().Count(c => c == 'A'), Is.EqualTo(0));
@@ -42,10 +40,8 @@ public void TryingToAddDisallowedOperatorCharacters_Should_Throw()
4240
public void ExistingOperatorCharacter_Should_Not_Be_Added()
4341
{
4442
var settings = new SmartSettings();
45-
#pragma warning disable CA1861 // Not called repeatedly
4643
settings.Parser.AddCustomOperatorChars(new[] {settings.Parser.OperatorChars()[0], '°'});
4744
settings.Parser.AddCustomOperatorChars(new[] {'°'});
48-
#pragma warning restore CA1861
4945

5046
Assert.Multiple(() =>
5147
{

src/SmartFormat.Tests/Extensions/ListFormatterTests.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,13 +170,11 @@ public void NestedArraysTest(string format, string expected)
170170
[Test, Description("Format a list of lists")]
171171
public void List_Of_Lists_With_Element_Format()
172172
{
173-
#pragma warning disable CA1861 // Not called repeatedly, but called with different arguments
174173
var data = new List<int[]> {
175174
new[] { 1, 2, 3 },
176175
new[] { 4, 5, 6 },
177176
new[] { 7, 8, 9 }
178177
};
179-
#pragma warning restore CA1861
180178

181179
var formatter = new SmartFormatter()
182180
.AddExtensions(new ListFormatter(), new DefaultSource())

src/SmartFormat.Tests/Extensions/PluralLocalizationFormatterTests.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,6 @@ public void NamedFormatter_should_use_specific_language(string format, object ar
270270
Assert.That(actualResult, Is.EqualTo(expectedResult));
271271
}
272272

273-
#pragma warning disable CA1861 // Not called repeatedly, but called with different arguments
274273
[TestCase("{0:plural:zero|one|many}", new string[0], "zero")]
275274
[TestCase("{0:plural:zero|one|many}", new[] { "alice" }, "one")]
276275
[TestCase("{0:plural:zero|one|many}", new[] { "alice", "bob" }, "many")]
@@ -281,7 +280,6 @@ public void Test_should_allow_ienumerable_parameter(string format, object arg0,
281280
var actualResult = smart.Format(culture, format, arg0);
282281
Assert.That(actualResult, Is.EqualTo(expectedResult));
283282
}
284-
#pragma warning restore CA1861
285283

286284
[Test]
287285
public void Test_With_CustomPluralRuleProvider()

src/SmartFormat.Tests/SmartFormat.Tests.csproj

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,14 @@
2929
</ItemGroup>
3030

3131
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
32+
<NoWarn>$(NoWarn);CA1861</NoWarn>
3233
<WarningLevel>4</WarningLevel>
3334
<DefineConstants>DEBUG;TRACE</DefineConstants>
3435
</PropertyGroup>
3536

3637
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
37-
<WarningLevel>3</WarningLevel>
38+
<NoWarn>$(NoWarn);CA1861</NoWarn>
39+
<WarningLevel>4</WarningLevel>
3840
<DefineConstants>RELEASE</DefineConstants>
3941
</PropertyGroup>
4042

src/SmartFormat.Tests/TestUtils/ReflectionTools.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,16 @@ IEnumerable<Type> GetAllAscendants(Type t)
3232
}
3333
}
3434

35+
#if NET6_0_OR_GREATER
36+
ArgumentNullException.ThrowIfNull(assembly, nameof(assembly));
37+
ArgumentNullException.ThrowIfNull(genericTypeDefinition, nameof(genericTypeDefinition));
38+
#else
3539
if (assembly == null)
3640
throw new ArgumentNullException(nameof(assembly));
3741

3842
if (genericTypeDefinition == null)
3943
throw new ArgumentNullException(nameof(genericTypeDefinition));
40-
44+
#endif
4145
if (!genericTypeDefinition.IsGenericTypeDefinition)
4246
throw new ArgumentException(
4347
@"Specified type is not a valid generic type definition.",
@@ -61,4 +65,4 @@ public static bool IsSubclassOf(Type typeToTest, Assembly assembly, Type generic
6165
{
6266
return GetSubclassesOf(assembly, genericTypeDefinition).Any(t => t == typeToTest);
6367
}
64-
}
68+
}

src/SmartFormat/Extensions/ConditionalFormatter.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public class ConditionalFormatter : IFormatter
1919
private static readonly Regex _complexConditionPattern
2020
= new(@"^ (?: ([&/]?) ([<>=!]=?) ([0-9.-]+) )+ \?",
2121
// Description: and/or comparator value
22-
RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
22+
RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled, TimeSpan.FromMilliseconds(500));
2323

2424
private char _splitChar = '|';
2525

@@ -127,7 +127,7 @@ public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
127127
case DateTime dateTimeArg when dateTimeArg.ToUniversalTime() <= SystemTime.Now().ToUniversalTime():
128128
paramIndex = 0;
129129
break;
130-
case DateTime dateTimeArg:
130+
case DateTime:
131131
paramIndex = paramCount - 1;
132132
break;
133133
// Date: Past|Present|Future or Past/Present|Future
@@ -239,4 +239,4 @@ private static bool TryEvaluateCondition(Format parameter, decimal value, out bo
239239
outputItem = parameter.Substring(newStartIndex);
240240
return true;
241241
}
242-
}
242+
}

0 commit comments

Comments
 (0)