* Apply csharp refactoring

* Reverted switch refactoring to if based on rule

* Fix leftover conflicts

* More refactoring

* wrapping long line arguments

* More refactoring

* More code cleanup

* Remove unused import
This commit is contained in:
Armaan Mcleod 2022-01-06 16:45:14 +11:00 коммит произвёл GitHub
Родитель 72480c81f5
Коммит 902765d803
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
92 изменённых файлов: 1225 добавлений и 1079 удалений

Просмотреть файл

@ -19,8 +19,10 @@ indent_size = 2
# C# files
[*.cs]
# Sort using and Import directives with System.* appearing first
# Code style defaults
csharp_using_directive_placement = outside_namespace:suggestion
dotnet_sort_system_directives_first = true
dotnet_style_readonly_field = true:suggestion
# License header
file_header_template = Copyright (c) Microsoft Corporation.\nLicensed under the MIT License.
@ -35,9 +37,11 @@ dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggesti
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_auto_properties = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
csharp_prefer_simple_default_expression = true:suggestion
# Use var when it's obvious what the variable type is
csharp_style_var_when_type_is_apparent = true:suggestion
# Prefer "var" everywhere
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion

Просмотреть файл

@ -55,10 +55,7 @@ namespace PSRule.Badges
private static double Find(char c)
{
var index = Array.BinarySearch(_Char, c);
if (index >= 0)
return _Width[index];
return 0d;
return index >= 0 ? _Width[index] : 0d;
}
public static double Measure(string s)

Просмотреть файл

@ -64,7 +64,7 @@ namespace PSRule.BuildTool
{
using var font = new Font("Verdana", 11f, GraphicsUnit.Pixel);
using var g = Graphics.FromHwnd(IntPtr.Zero);
SizeF size = g.MeasureString(s, font);
var size = g.MeasureString(s, font);
return size.Width;
}
}

Просмотреть файл

@ -91,7 +91,14 @@ namespace PSRule.Badges
var w = (int)Math.Round(_LeftWidth + _RightWidth + 2 * _BorderPadding + 2 * _MidPadding);
var x = (int)Math.Round(_LeftWidth + _BorderPadding + _MidPadding);
var builder = new SvgBuilder(width: w, height: 20, textScale: 10, midPoint: x, rounding: 2, borderPadding: _BorderPadding, midPadding: _MidPadding);
var builder = new SvgBuilder(
width: w,
height: 20,
textScale: 10,
midPoint: x,
rounding: 2,
borderPadding: _BorderPadding,
midPadding: _MidPadding);
builder.Begin(string.Concat(_LeftText, ": ", _RightText));
builder.Backfill(_Fill);
builder.TextBlock(_LeftText, _RightText, 110);

Просмотреть файл

@ -23,7 +23,11 @@ namespace PSRule.Commands
var invokeResult = RuleConditionHelper.Create(Body.Invoke());
var result = invokeResult.AllOf();
RunspaceContext.CurrentThread.VerboseConditionResult(condition: RuleLanguageNouns.AllOf, pass: invokeResult.Pass, count: invokeResult.Count, outcome: result);
RunspaceContext.CurrentThread.VerboseConditionResult(
condition: RuleLanguageNouns.AllOf,
pass: invokeResult.Pass,
count: invokeResult.Count,
outcome: result);
WriteObject(result);
}
}

Просмотреть файл

@ -23,7 +23,11 @@ namespace PSRule.Commands
var invokeResult = RuleConditionHelper.Create(Body.Invoke());
var result = invokeResult.AnyOf();
RunspaceContext.CurrentThread.VerboseConditionResult(condition: RuleLanguageNouns.AnyOf, pass: invokeResult.Pass, count: invokeResult.Count, outcome: result);
RunspaceContext.CurrentThread.VerboseConditionResult(
condition: RuleLanguageNouns.AnyOf,
pass: invokeResult.Pass,
count: invokeResult.Count,
outcome: result);
WriteObject(result);
}
}

Просмотреть файл

@ -52,14 +52,22 @@ namespace PSRule.Commands
var targetObject = InputObject ?? GetTargetObject();
var foundFields = new List<string>();
var notFoundFields = new List<string>();
int found = 0;
int required = All ? Field.Length : 1;
var found = 0;
var required = All ? Field.Length : 1;
for (var i = 0; i < Field.Length && found < required; i++)
{
if (ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: targetObject, path: Field[i], caseSensitive: CaseSensitive, value: out object _))
if (ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: targetObject,
path: Field[i],
caseSensitive: CaseSensitive,
value: out object _))
{
RunspaceContext.CurrentThread.VerboseConditionMessage(condition: RuleLanguageNouns.Exists, message: PSRuleResources.ExistsTrue, args: Field[i]);
RunspaceContext.CurrentThread.VerboseConditionMessage(
condition: RuleLanguageNouns.Exists,
message: PSRuleResources.ExistsTrue,
args: Field[i]);
foundFields.Add(Field[i]);
found++;
}
@ -71,7 +79,13 @@ namespace PSRule.Commands
RunspaceContext.CurrentThread.VerboseConditionResult(condition: RuleLanguageNouns.Exists, outcome: result);
if (!(result || TryReason(Reason)))
{
WriteReason(Not ? string.Format(Thread.CurrentThread.CurrentCulture, ReasonStrings.ExistsNot, string.Join(", ", foundFields)) : string.Format(Thread.CurrentThread.CurrentCulture, ReasonStrings.Exists, string.Join(", ", notFoundFields)));
WriteReason(Not ? string.Format(
Thread.CurrentThread.CurrentCulture,
ReasonStrings.ExistsNot,
string.Join(", ", foundFields)) : string.Format(
Thread.CurrentThread.CurrentCulture,
ReasonStrings.Exists,
string.Join(", ", notFoundFields)));
}
WriteObject(result);
}

Просмотреть файл

@ -62,20 +62,28 @@ namespace PSRule.Commands
throw RuleScopeException(LanguageKeywords.Match);
var targetObject = InputObject ?? GetTargetObject();
bool expected = !Not;
bool match = false;
string found = string.Empty;
var expected = !Not;
var match = false;
var found = string.Empty;
// Pass with any match, or (-Not) fail with any match
if (ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: targetObject, path: Field, caseSensitive: false, value: out object fieldValue))
if (ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: targetObject,
path: Field,
caseSensitive: false,
value: out object fieldValue))
{
for (var i = 0; i < _Expressions.Length && !match; i++)
{
if (_Expressions[i].IsMatch(fieldValue.ToString()))
{
match = true;
RunspaceContext.CurrentThread.VerboseConditionMessage(condition: RuleLanguageNouns.Match, message: PSRuleResources.MatchTrue, args: fieldValue);
RunspaceContext.CurrentThread.VerboseConditionMessage(
condition: RuleLanguageNouns.Match,
message: PSRuleResources.MatchTrue,
args: fieldValue);
found = Expression[i];
}
}
@ -85,7 +93,13 @@ namespace PSRule.Commands
RunspaceContext.CurrentThread.VerboseConditionResult(condition: RuleLanguageNouns.Match, outcome: result);
if (!(result || TryReason(Reason)))
{
WriteReason(Not ? string.Format(Thread.CurrentThread.CurrentCulture, ReasonStrings.MatchNot, found) : string.Format(Thread.CurrentThread.CurrentCulture, ReasonStrings.Match, string.Join(", ", Expression)));
WriteReason(Not ? string.Format(
Thread.CurrentThread.CurrentCulture,
ReasonStrings.MatchNot,
found) : string.Format(
Thread.CurrentThread.CurrentCulture,
ReasonStrings.Match,
string.Join(", ", Expression)));
}
WriteObject(result);
}

Просмотреть файл

@ -63,13 +63,18 @@ namespace PSRule.Commands
throw RuleScopeException(LanguageKeywords.Within);
var targetObject = InputObject ?? GetTargetObject();
bool expected = !Not;
bool match = false;
string found = string.Empty;
var expected = !Not;
var match = false;
var found = string.Empty;
// Pass with any match, or (-Not) fail with any match
if (ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: targetObject, path: Field, caseSensitive: false, value: out object fieldValue))
if (ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: targetObject,
path: Field,
caseSensitive: false,
value: out object fieldValue))
{
for (var i = 0; (Value == null || i < Value.Length) && !match; i++)
{
@ -79,7 +84,10 @@ namespace PSRule.Commands
if (fieldValue == null && (Value == null || Value[i] == null))
{
match = true;
RunspaceContext.CurrentThread.VerboseConditionMessage(condition: RuleLanguageNouns.Within, message: PSRuleResources.WithinTrue, args: fieldValue);
RunspaceContext.CurrentThread.VerboseConditionMessage(
condition: RuleLanguageNouns.Within,
message: PSRuleResources.WithinTrue,
args: fieldValue);
}
else
{
@ -92,7 +100,10 @@ namespace PSRule.Commands
if ((_LikePattern == null && _Comparer.Equals(Value[i].BaseObject, strValue)) || (_LikePattern != null && _LikePattern[i].IsMatch(strValue)))
{
match = true;
RunspaceContext.CurrentThread.VerboseConditionMessage(condition: RuleLanguageNouns.Within, message: PSRuleResources.WithinTrue, args: strValue);
RunspaceContext.CurrentThread.VerboseConditionMessage(
condition: RuleLanguageNouns.Within,
message: PSRuleResources.WithinTrue,
args: strValue);
found = Value[i].BaseObject.ToString();
}
}
@ -100,7 +111,10 @@ namespace PSRule.Commands
else if (Value[i].Equals(fieldValue))
{
match = true;
RunspaceContext.CurrentThread.VerboseConditionMessage(condition: RuleLanguageNouns.Within, message: PSRuleResources.WithinTrue, args: fieldValue);
RunspaceContext.CurrentThread.VerboseConditionMessage(
condition: RuleLanguageNouns.Within,
message: PSRuleResources.WithinTrue,
args: fieldValue);
found = Value[i].ToString();
}
}
@ -126,7 +140,7 @@ namespace PSRule.Commands
_LikePattern = new WildcardPattern[Value.Length];
for (var i = 0; i < _LikePattern.Length; i++)
{
if (!TryStringValue(Value[i], out string value))
if (!TryStringValue(Value[i], out var value))
{
throw new RuleException(PSRuleResources.WithinLikeNotString);
}
@ -137,7 +151,7 @@ namespace PSRule.Commands
private bool TryExpressionCache()
{
if (!PipelineContext.CurrentThread.ExpressionCache.TryGetValue(MyInvocation.PositionMessage, out object cacheValue))
if (!PipelineContext.CurrentThread.ExpressionCache.TryGetValue(MyInvocation.PositionMessage, out var cacheValue))
return false;
_LikePattern = (WildcardPattern[])cacheValue;

Просмотреть файл

@ -42,10 +42,9 @@ namespace PSRule.Commands
protected ActionPreference? GetBoundPreference(string name)
{
if (MyInvocation.BoundParameters.ContainsKey(name) && Enum.TryParse(MyInvocation.BoundParameters[name].ToString(), out ActionPreference value))
return value;
return null;
return MyInvocation.BoundParameters.ContainsKey(name) && Enum.TryParse(MyInvocation.BoundParameters[name].ToString(), out ActionPreference value)
? (ActionPreference?)value
: null;
}
}
}

Просмотреть файл

@ -20,7 +20,7 @@ namespace PSRule
public static bool TryPopValue<T>(this IDictionary<string, object> dictionary, string key, out T value)
{
value = default;
if (dictionary.TryGetValue(key, out object v) && dictionary.Remove(key) && v is T result)
if (dictionary.TryGetValue(key, out var v) && dictionary.Remove(key) && v is T result)
{
value = result;
return true;
@ -32,21 +32,21 @@ namespace PSRule
public static bool TryPopBool(this IDictionary<string, object> dictionary, string key, out bool value)
{
value = default;
return TryPopValue(dictionary, key, out object v) && bool.TryParse(v.ToString(), out value);
return TryPopValue(dictionary, key, out var v) && bool.TryParse(v.ToString(), out value);
}
[DebuggerStepThrough]
public static bool TryPopEnum<TEnum>(this IDictionary<string, object> dictionary, string key, out TEnum value) where TEnum : struct
{
value = default;
return TryPopValue(dictionary, key, out object v) && Enum.TryParse(v.ToString(), ignoreCase: true, result: out value);
return TryPopValue(dictionary, key, out var v) && Enum.TryParse(v.ToString(), ignoreCase: true, result: out value);
}
[DebuggerStepThrough]
public static bool TryPopString(this IDictionary<string, object> dictionary, string key, out string value)
{
value = default;
if (TryPopValue(dictionary, key, out object v) && v is string svalue)
if (TryPopValue(dictionary, key, out var v) && v is string svalue)
{
value = svalue;
return true;
@ -58,14 +58,14 @@ namespace PSRule
public static bool TryPopStringArray(this IDictionary<string, object> dictionary, string key, out string[] value)
{
value = default;
return TryPopValue(dictionary, key, out object v) && TryStringArray(v, out value);
return TryPopValue(dictionary, key, out var v) && TryStringArray(v, out value);
}
[DebuggerStepThrough]
public static bool TryGetBool(this IDictionary<string, object> dictionary, string key, out bool? value)
{
value = null;
if (!dictionary.TryGetValue(key, out object o))
if (!dictionary.TryGetValue(key, out var o))
return false;
if (o is bool bvalue || (o is string svalue && bool.TryParse(svalue, out bvalue)))
@ -80,7 +80,7 @@ namespace PSRule
public static bool TryGetLong(this IDictionary<string, object> dictionary, string key, out long? value)
{
value = null;
if (!dictionary.TryGetValue(key, out object o))
if (!dictionary.TryGetValue(key, out var o))
return false;
if (o is long lvalue || (o is string svalue && long.TryParse(svalue, out lvalue)))
@ -95,7 +95,7 @@ namespace PSRule
public static bool TryGetString(this IDictionary<string, object> dictionary, string key, out string value)
{
value = null;
if (!dictionary.TryGetValue(key, out object o))
if (!dictionary.TryGetValue(key, out var o))
return false;
if (o is string svalue)
@ -110,10 +110,7 @@ namespace PSRule
public static bool TryGetStringArray(this IDictionary<string, object> dictionary, string key, out string[] value)
{
value = null;
if (!dictionary.TryGetValue(key, out object o))
return false;
return TryStringArray(o, out value);
return dictionary.TryGetValue(key, out var o) && TryStringArray(o, out value);
}
[DebuggerStepThrough]

Просмотреть файл

@ -12,31 +12,28 @@ namespace PSRule
{
public static bool IsAzurePipelines(this EnvironmentHelper helper)
{
return helper.TryBool("TF_BUILD", out bool azp) && azp;
return helper.TryBool("TF_BUILD", out var azp) && azp;
}
public static bool IsGitHubActions(this EnvironmentHelper helper)
{
return helper.TryBool("GITHUB_ACTIONS", out bool gh) && gh;
return helper.TryBool("GITHUB_ACTIONS", out var gh) && gh;
}
public static bool IsVisualStudioCode(this EnvironmentHelper helper)
{
return helper.TryString("TERM_PROGRAM", out string term) && term == "vscode";
return helper.TryString("TERM_PROGRAM", out var term) && term == "vscode";
}
public static string GetRunId(this EnvironmentHelper helper)
{
if (helper.TryString("PSRULE_RUN_ID", out string runId))
if (helper.TryString("PSRULE_RUN_ID", out var runId))
return runId;
if (helper.TryString("BUILD_REPOSITORY_NAME", out string prefix) && helper.TryString("BUILD_BUILDID", out string suffix))
return string.Concat(prefix, "/", suffix);
if (helper.TryString("GITHUB_REPOSITORY", out prefix) && helper.TryString("GITHUB_RUN_ID", out suffix))
return string.Concat(prefix, "/", suffix);
return null;
return helper.TryString("BUILD_REPOSITORY_NAME", out var prefix) && helper.TryString("BUILD_BUILDID", out var suffix) ||
helper.TryString("GITHUB_REPOSITORY", out prefix) && helper.TryString("GITHUB_RUN_ID", out suffix)
? string.Concat(prefix, "/", suffix)
: null;
}
}
@ -54,7 +51,7 @@ namespace PSRule
internal bool TrySecureString(string key, out SecureString value)
{
value = null;
if (!TryString(key, out string variable))
if (!TryString(key, out var variable))
return false;
value = new NetworkCredential("na", variable).SecurePassword;
@ -64,28 +61,25 @@ namespace PSRule
internal bool TryInt(string key, out int value)
{
value = default;
return TryVariable(key, out string variable) && int.TryParse(variable, out value);
return TryVariable(key, out var variable) && int.TryParse(variable, out value);
}
internal bool TryBool(string key, out bool value)
{
value = default;
return TryVariable(key, out string variable) && TryParseBool(variable, out value);
return TryVariable(key, out var variable) && TryParseBool(variable, out value);
}
internal bool TryEnum<TEnum>(string key, out TEnum value) where TEnum : struct
{
value = default;
if (!TryVariable(key, out string variable))
return false;
return Enum.TryParse(variable, ignoreCase: true, out value);
return TryVariable(key, out var variable) && Enum.TryParse(variable, ignoreCase: true, out value);
}
internal bool TryStringArray(string key, out string[] value)
{
value = default;
if (!TryVariable(key, out string variable))
if (!TryVariable(key, out var variable))
return false;
value = variable.Split(STRINGARRAY_SEPARATOR, options: StringSplitOptions.RemoveEmptyEntries);
@ -103,7 +97,7 @@ namespace PSRule
if (bool.TryParse(variable, out value))
return true;
if (int.TryParse(variable, out int ivalue))
if (int.TryParse(variable, out var ivalue))
{
value = ivalue > 0;
return true;

Просмотреть файл

@ -32,7 +32,7 @@ namespace PSRule
o = GetBaseObject(o);
return (o is ICollection c && c.Count == 0) ||
(TryString(o, out string s) && string.IsNullOrEmpty(s));
(TryString(o, out var s) && string.IsNullOrEmpty(s));
}
internal static bool Exists(IBindingContext bindingContext, object inputObject, string field, bool caseSensitive)
@ -42,16 +42,16 @@ namespace PSRule
internal static bool Equal(object expectedValue, object actualValue, bool caseSensitive, bool convertExpected = false, bool convertActual = false)
{
if (TryString(expectedValue, out string s1) && TryString(actualValue, out string s2))
if (TryString(expectedValue, out var s1) && TryString(actualValue, out var s2))
return StringEqual(s1, s2, caseSensitive);
if (TryBool(expectedValue, convertExpected, out bool b1) && TryBool(actualValue, convertActual, out bool b2))
if (TryBool(expectedValue, convertExpected, out var b1) && TryBool(actualValue, convertActual, out var b2))
return b1 == b2;
if (TryLong(expectedValue, convertExpected, out long l1) && TryLong(actualValue, convertActual, out long l2))
if (TryLong(expectedValue, convertExpected, out var l1) && TryLong(actualValue, convertActual, out var l2))
return l1 == l2;
if (TryInt(expectedValue, convertExpected, out int i1) && TryInt(actualValue, convertActual, out int i2))
if (TryInt(expectedValue, convertExpected, out var i1) && TryInt(actualValue, convertActual, out var i2))
return i1 == i2;
var expectedBase = GetBaseObject(expectedValue);
@ -61,31 +61,33 @@ namespace PSRule
internal static bool CompareNumeric(object actual, object expected, bool convert, out int compare, out object value)
{
if (TryInt(actual, convert, out int actualInt) && TryInt(expected, convert: true, value: out int expectedInt))
if (TryInt(actual, convert, out var actualInt) && TryInt(expected, convert: true, value: out var expectedInt))
{
compare = Comparer<int>.Default.Compare(actualInt, expectedInt);
value = actualInt;
return true;
}
else if (TryLong(actual, convert, out long actualLong) && TryLong(expected, convert: true, value: out long expectedLong))
else if (TryLong(actual, convert, out var actualLong) && TryLong(expected, convert: true, value: out var expectedLong))
{
compare = Comparer<long>.Default.Compare(actualLong, expectedLong);
value = actualLong;
return true;
}
else if (TryFloat(actual, convert, out float actualFloat) && TryFloat(expected, convert: true, value: out float expectedFloat))
else if (TryFloat(actual, convert, out var actualFloat) && TryFloat(expected, convert: true, value: out var expectedFloat))
{
compare = Comparer<float>.Default.Compare(actualFloat, expectedFloat);
value = actualFloat;
return true;
}
else if (TryDateTime(actual, convert, out DateTime actualDateTime) && TryDateTime(expected, convert: true, value: out DateTime expectedDateTime))
else if (TryDateTime(actual, convert, out var actualDateTime) && TryDateTime(expected, convert: true, value: out var expectedDateTime))
{
compare = Comparer<DateTime>.Default.Compare(actualDateTime, expectedDateTime);
value = actualDateTime;
return true;
}
else if ((TryStringLength(actual, out actualInt) || TryEnumerableLength(actual, out actualInt)) && TryInt(expected, convert: true, value: out expectedInt))
else if ((TryStringLength(actual, out actualInt) ||
TryEnumerableLength(actual, out actualInt)) &&
TryInt(expected, convert: true, value: out expectedInt))
{
compare = Comparer<int>.Default.Compare(actualInt, expectedInt);
value = actualInt;
@ -118,7 +120,7 @@ namespace PSRule
if (TryString(o, out value))
return true;
if (TryInt(o, false, out int ivalue))
if (TryInt(o, false, out var ivalue))
{
value = ivalue.ToString(Thread.CurrentThread.CurrentCulture);
return true;
@ -129,7 +131,7 @@ namespace PSRule
internal static bool TryConvertStringArray(object[] o, out string[] value)
{
value = Array.Empty<string>();
if (o == null || o.Length == 0 || !TryConvertString(o[0], out string s))
if (o == null || o.Length == 0 || !TryConvertString(o[0], out var s))
return false;
value = new string[o.Length];
@ -163,7 +165,7 @@ namespace PSRule
value = token.Value<int>();
return true;
}
else if (convert && TryString(o, out string s) && int.TryParse(s, out ivalue))
else if (convert && TryString(o, out var s) && int.TryParse(s, out ivalue))
{
value = ivalue;
return true;
@ -185,7 +187,7 @@ namespace PSRule
value = token.Value<bool>();
return true;
}
else if (convert && TryString(o, out string s) && bool.TryParse(s, out bvalue))
else if (convert && TryString(o, out var s) && bool.TryParse(s, out bvalue))
{
value = bvalue;
return true;
@ -207,7 +209,7 @@ namespace PSRule
value = token.Value<byte>();
return true;
}
else if (convert && TryString(o, out string s) && byte.TryParse(s, out bvalue))
else if (convert && TryString(o, out var s) && byte.TryParse(s, out bvalue))
{
value = bvalue;
return true;
@ -239,7 +241,7 @@ namespace PSRule
value = token.Value<long>();
return true;
}
else if (convert && TryString(o, out string s) && long.TryParse(s, out l))
else if (convert && TryString(o, out var s) && long.TryParse(s, out l))
{
value = l;
return true;
@ -329,12 +331,12 @@ namespace PSRule
value = token.Value<DateTime>();
return true;
}
else if (convert && TryString(o, out string s) && DateTime.TryParse(s, out dvalue))
else if (convert && TryString(o, out var s) && DateTime.TryParse(s, out dvalue))
{
value = dvalue;
return true;
}
else if (convert && TryInt(o, convert: false, out int daysOffset))
else if (convert && TryInt(o, convert: false, out var daysOffset))
{
value = DateTime.Now.AddDays(daysOffset);
return true;
@ -351,7 +353,7 @@ namespace PSRule
internal static bool Match(object pattern, object value, bool caseSensitive)
{
return TryString(pattern, out string patternString) && TryString(value, out string s) && Match(patternString, s, caseSensitive);
return TryString(pattern, out var patternString) && TryString(value, out var s) && Match(patternString, s, caseSensitive);
}
internal static bool AnyValue(object actualValue, object expectedValue, bool caseSensitive, out object foundValue)
@ -440,7 +442,7 @@ namespace PSRule
private static string NormalizeSchemaUri(string value, bool ignoreScheme)
{
if (!Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out Uri uri))
if (!Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out var uri))
return value;
var result = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.ToString();
@ -481,7 +483,7 @@ namespace PSRule
private static bool TryPipelineCache<T>(string prefix, string key, out T value)
{
value = default;
if (PipelineContext.CurrentThread.ExpressionCache.TryGetValue(string.Concat(prefix, key), out object ovalue))
if (PipelineContext.CurrentThread.ExpressionCache.TryGetValue(string.Concat(prefix, key), out var ovalue))
{
value = (T)ovalue;
return true;
@ -501,36 +503,32 @@ namespace PSRule
private static PSRuleTargetInfo GetTargetInfo(object o)
{
return o is PSObject pso && pso.TryTargetInfo(out PSRuleTargetInfo targetInfo) ? targetInfo : null;
return o is PSObject pso && pso.TryTargetInfo(out var targetInfo) ? targetInfo : null;
}
private static bool StringEqual(string expectedValue, string actualValue, bool caseSensitive)
{
return caseSensitive ? StringComparer.Ordinal.Equals(expectedValue, actualValue) : StringComparer.OrdinalIgnoreCase.Equals(expectedValue, actualValue);
return caseSensitive
? StringComparer.Ordinal.Equals(expectedValue, actualValue)
: StringComparer.OrdinalIgnoreCase.Equals(expectedValue, actualValue);
}
internal static bool StartsWith(string actualValue, object expectedValue, bool caseSensitive)
{
if (!TryString(expectedValue, out string expected))
return false;
return actualValue.StartsWith(expected, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
return TryString(expectedValue, out var expected) &&
actualValue.StartsWith(expected, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
internal static bool EndsWith(string actualValue, object expectedValue, bool caseSensitive)
{
if (!TryString(expectedValue, out string expected))
return false;
return actualValue.EndsWith(expected, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
return TryString(expectedValue, out var expected)
&& actualValue.EndsWith(expected, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
internal static bool Contains(string actualValue, object expectedValue, bool caseSensitive)
{
if (!TryString(expectedValue, out string expected))
return false;
return actualValue.IndexOf(expected, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) >= 0;
return TryString(expectedValue, out var expected)
&& actualValue.IndexOf(expected, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) >= 0;
}
internal static bool IsLower(string actualValue, bool requireLetters, out bool notLetter)

Просмотреть файл

@ -10,7 +10,7 @@ namespace PSRule
public static string GetHeadRef(string path)
{
// Try PSRule
if (EnvironmentHelper.Default.TryString("PSRULE_GITREF", out string value))
if (EnvironmentHelper.Default.TryString("PSRULE_GITREF", out var value))
return value;
// Try Azure Pipelines
@ -22,10 +22,7 @@ namespace PSRule
return value;
// Try .git/HEAD
if (TryReadHead(path, out value))
return value;
return null;
return TryReadHead(path, out value) ? value : null;
}
private static bool TryReadHead(string path, out string value)
@ -39,10 +36,7 @@ namespace PSRule
if (lines == null || lines.Length == 0)
return false;
if (lines[0].StartsWith("ref: ", System.StringComparison.OrdinalIgnoreCase))
value = lines[0].Substring(5);
else
value = lines[0];
value = lines[0].StartsWith("ref: ", System.StringComparison.OrdinalIgnoreCase) ? lines[0].Substring(5) : lines[0];
return true;
}

Просмотреть файл

@ -234,7 +234,7 @@ namespace PSRule
}
if (bindTargetInfo)
{
result.UseTargetInfo(out PSRuleTargetInfo info);
result.UseTargetInfo(out var info);
info.SetSource(sourceInfo?.File, lineNumber, linePosition);
}
return result;
@ -409,13 +409,13 @@ namespace PSRule
var propertyName = reader.Value.ToString();
// Read apiVersion
if (TryApiVersion(reader: reader, propertyName: propertyName, apiVersion: out string apiVersionValue))
if (TryApiVersion(reader: reader, propertyName: propertyName, apiVersion: out var apiVersionValue))
{
apiVersion = apiVersionValue;
}
// Read kind
else if (TryKind(reader: reader, propertyName: propertyName, kind: out string kindValue))
else if (TryKind(reader: reader, propertyName: propertyName, kind: out var kindValue))
{
kind = kindValue;
}
@ -425,7 +425,7 @@ namespace PSRule
reader: reader,
serializer: serializer,
propertyName: propertyName,
metadata: out ResourceMetadata metadataValue))
metadata: out var metadataValue))
{
metadata = metadataValue;
}
@ -439,7 +439,7 @@ namespace PSRule
kind: kind,
metadata: metadata,
comment: comment,
spec: out IResource specValue))
spec: out var specValue))
{
result = specValue;
@ -533,7 +533,7 @@ namespace PSRule
if (propertyName == FIELD_SPEC && _Factory.TryDescriptor(
apiVersion: apiVersion,
name: kind,
descriptor: out ISpecDescriptor descriptor))
descriptor: out var descriptor))
{
if (reader.Read() && reader.TokenType == JsonToken.StartObject)
{
@ -702,7 +702,7 @@ namespace PSRule
var properties = new LanguageExpression.PropertyBag();
MapProperty(properties, reader, out string key);
MapProperty(properties, reader, out var key);
if (key != null && TryCondition(key))
{
@ -790,7 +790,7 @@ namespace PSRule
{
expression = null;
if (_Factory.TryDescriptor(type, out ILanguageExpresssionDescriptor descriptor))
if (_Factory.TryDescriptor(type, out var descriptor))
{
expression = (T)descriptor.CreateInstance(
source: RunspaceContext.CurrentThread.Source.File,

Просмотреть файл

@ -130,7 +130,7 @@ namespace PSRule
foreach (var variable in env.WithPrefix(prefix))
{
if (TryKeyPrefix(variable.Key, prefix, out string suffix))
if (TryKeyPrefix(variable.Key, prefix, out var suffix))
{
if (format != null)
suffix = format(suffix);
@ -154,7 +154,7 @@ namespace PSRule
var keys = dictionary.Keys.ToArray();
for (var i = 0; i < keys.Length; i++)
{
if (TryKeyPrefix(keys[i], prefix, out string suffix) && dictionary.TryPopValue(keys[i], out object value))
if (TryKeyPrefix(keys[i], prefix, out var suffix) && dictionary.TryPopValue(keys[i], out var value))
_Map[suffix] = (TValue)value;
}
}
@ -181,7 +181,7 @@ namespace PSRule
if (binder == null)
throw new ArgumentNullException(nameof(binder));
var found = _Map.TryGetValue(binder.Name, out TValue value);
var found = _Map.TryGetValue(binder.Name, out var value);
result = value;
return found;
}

Просмотреть файл

@ -19,23 +19,21 @@ namespace PSRule
public static T PropertyValue<T>(this PSObject o, string propertyName)
{
if (o.BaseObject is Hashtable hashtable)
return ConvertValue<T>(hashtable[propertyName]);
return ConvertValue<T>(o.Properties[propertyName].Value);
return o.BaseObject is Hashtable hashtable
? ConvertValue<T>(hashtable[propertyName])
: ConvertValue<T>(o.Properties[propertyName].Value);
}
public static PSObject PropertyValue(this PSObject o, string propertyName)
{
if (o.BaseObject is Hashtable hashtable)
return PSObject.AsPSObject(hashtable[propertyName]);
return PSObject.AsPSObject(o.Properties[propertyName].Value);
return o.BaseObject is Hashtable hashtable
? PSObject.AsPSObject(hashtable[propertyName])
: PSObject.AsPSObject(o.Properties[propertyName].Value);
}
public static string ValueAsString(this PSObject o, string propertyName, bool caseSensitive)
{
return ObjectHelper.GetPath(o, propertyName, caseSensitive, out object value) && value != null ? value.ToString() : null;
return ObjectHelper.GetPath(o, propertyName, caseSensitive, out var value) && value != null ? value.ToString() : null;
}
public static bool HasProperty(this PSObject o, string propertyName)
@ -70,7 +68,13 @@ namespace PSRule
public static string ToJson(this PSObject o)
{
var settings = new JsonSerializerSettings { Formatting = Formatting.None, TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024, Culture = CultureInfo.InvariantCulture };
var settings = new JsonSerializerSettings
{
Formatting = Formatting.None,
TypeNameHandling = TypeNameHandling.None,
MaxDepth = 1024,
Culture = CultureInfo.InvariantCulture
};
settings.Converters.Insert(0, new PSObjectJsonConverter());
return JsonConvert.SerializeObject(o, settings);
}
@ -91,7 +95,7 @@ namespace PSRule
public static void SetTargetInfo(this PSObject o, PSRuleTargetInfo targetInfo)
{
if (TryTargetInfo(o, out PSRuleTargetInfo orginalInfo))
if (TryTargetInfo(o, out var orginalInfo))
{
targetInfo.Combine(orginalInfo);
o.Members[PSRuleTargetInfo.PropertyName].Value = targetInfo;
@ -102,18 +106,12 @@ namespace PSRule
public static TargetSourceInfo[] GetSourceInfo(this PSObject o)
{
if (!TryTargetInfo(o, out PSRuleTargetInfo targetInfo))
return Array.Empty<TargetSourceInfo>();
return targetInfo.Source.ToArray();
return o.TryTargetInfo(out var targetInfo) ? targetInfo.Source.ToArray() : Array.Empty<TargetSourceInfo>();
}
public static TargetIssueInfo[] GetIssueInfo(this PSObject o)
{
if (!TryTargetInfo(o, out PSRuleTargetInfo targetInfo))
return Array.Empty<TargetIssueInfo>();
return targetInfo.Issue.ToArray();
return o.TryTargetInfo(out var targetInfo) ? targetInfo.Issue.ToArray() : Array.Empty<TargetIssueInfo>();
}
public static void ConvertTargetInfoProperty(this PSObject o)
@ -121,7 +119,7 @@ namespace PSRule
if (o == null || !TryProperty(o, PSRuleTargetInfo.PropertyName, out PSObject value))
return;
UseTargetInfo(o, out PSRuleTargetInfo targetInfo);
UseTargetInfo(o, out var targetInfo);
if (TryProperty(value, PROPERTY_SOURCE, out Array sources))
{
for (var i = 0; i < sources.Length; i++)

Просмотреть файл

@ -29,7 +29,14 @@ namespace PSRule.Common
private static bool IsEscapableCharacter(char c)
{
return c == Backslash || c == BracketOpen || c == ParenthesesOpen || c == AngleOpen || c == AngleClose || c == Backtick || c == BracketClose || c == ParenthesesClose;
return c == Backslash ||
c == BracketOpen ||
c == ParenthesesOpen ||
c == AngleOpen ||
c == AngleClose ||
c == Backtick ||
c == BracketClose ||
c == ParenthesesClose;
}
}
}

Просмотреть файл

@ -512,22 +512,22 @@ namespace PSRule
while (reader.TryConsume(out Scalar scalar))
{
// Read apiVersion
if (TryApiVersion(reader, scalar, out string apiVersionValue))
if (TryApiVersion(reader, scalar, out var apiVersionValue))
{
apiVersion = apiVersionValue;
}
// Read kind
else if (TryKind(reader, scalar, out string kindValue))
else if (TryKind(reader, scalar, out var kindValue))
{
kind = kindValue;
}
// Read metadata
else if (TryMetadata(reader, scalar, nestedObjectDeserializer, out ResourceMetadata metadataValue))
else if (TryMetadata(reader, scalar, nestedObjectDeserializer, out var metadataValue))
{
metadata = metadataValue;
}
// Read spec
else if (kind != null && TrySpec(reader, scalar, apiVersion, kind, nestedObjectDeserializer, metadata, comment, out IResource resource))
else if (kind != null && TrySpec(reader, scalar, apiVersion, kind, nestedObjectDeserializer, metadata, comment, out var resource))
{
result = resource;
}
@ -572,7 +572,7 @@ namespace PSRule
if (reader.Current is MappingStart)
{
if (!_Next.Deserialize(reader, typeof(ResourceMetadata), nestedObjectDeserializer, out object value))
if (!_Next.Deserialize(reader, typeof(ResourceMetadata), nestedObjectDeserializer, out var value))
return false;
metadata = (ResourceMetadata)value;
@ -584,18 +584,15 @@ namespace PSRule
private bool TrySpec(IParser reader, Scalar scalar, string apiVersion, string kind, Func<IParser, Type, object> nestedObjectDeserializer, ResourceMetadata metadata, CommentMetadata comment, out IResource spec)
{
spec = null;
if (scalar.Value != FIELD_SPEC)
return false;
return TryResource(reader, apiVersion, kind, nestedObjectDeserializer, metadata, comment, out spec);
return scalar.Value == FIELD_SPEC && TryResource(reader, apiVersion, kind, nestedObjectDeserializer, metadata, comment, out spec);
}
private bool TryResource(IParser reader, string apiVersion, string kind, Func<IParser, Type, object> nestedObjectDeserializer, ResourceMetadata metadata, CommentMetadata comment, out IResource spec)
{
spec = null;
if (_Factory.TryDescriptor(apiVersion, kind, out ISpecDescriptor descriptor) && reader.Current is MappingStart)
if (_Factory.TryDescriptor(apiVersion, kind, out var descriptor) && reader.Current is MappingStart)
{
if (!_Next.Deserialize(reader, descriptor.SpecType, nestedObjectDeserializer, out object value))
if (!_Next.Deserialize(reader, descriptor.SpecType, nestedObjectDeserializer, out var value))
return false;
spec = descriptor.CreateInstance(RunspaceContext.CurrentThread.Source.File, metadata, comment, value);
@ -679,7 +676,7 @@ namespace PSRule
{
LanguageExpression result = null;
var properties = new LanguageExpression.PropertyBag();
MapProperty(properties, reader, nestedObjectDeserializer, out string key);
MapProperty(properties, reader, nestedObjectDeserializer, out var key);
if (key != null && TryCondition(key))
{
result = MapCondition(key, properties, reader, nestedObjectDeserializer);
@ -700,7 +697,7 @@ namespace PSRule
name = null;
while (reader.TryConsume(out Scalar scalar))
{
string key = scalar.Value;
var key = scalar.Value;
if (TryCondition(key) || TryOperator(key))
name = key;
@ -736,7 +733,7 @@ namespace PSRule
private bool TryExpression<T>(IParser reader, string type, Func<IParser, Type, object> nestedObjectDeserializer, out T expression) where T : LanguageExpression
{
expression = null;
if (_Factory.TryDescriptor(type, out ILanguageExpresssionDescriptor descriptor))
if (_Factory.TryDescriptor(type, out var descriptor))
{
expression = (T)descriptor.CreateInstance(RunspaceContext.CurrentThread.Source.File, null);
return expression != null;
@ -762,12 +759,12 @@ namespace PSRule
{
if (expectedType == typeof(PSObject[]) && reader.Current is MappingStart)
{
int lineNumber = reader.Current.Start.Line;
int linePosition = reader.Current.Start.Column;
var lineNumber = reader.Current.Start.Line;
var linePosition = reader.Current.Start.Column;
value = _Converter.ReadYaml(reader, typeof(PSObject));
if (value is PSObject pso)
{
pso.UseTargetInfo(out PSRuleTargetInfo info);
pso.UseTargetInfo(out var info);
info.SetSource(_SourceInfo?.File, lineNumber, linePosition);
value = new PSObject[] { pso };
return true;

Просмотреть файл

@ -68,34 +68,34 @@ namespace PSRule.Configuration
{
// Binding.Field - currently not supported
if (env.TryBool("PSRULE_BINDING_IGNORECASE", out bool ignoreCase))
if (env.TryBool("PSRULE_BINDING_IGNORECASE", out var ignoreCase))
option.Binding.IgnoreCase = ignoreCase;
if (env.TryString("PSRULE_BINDING_NAMESEPARATOR", out string nameSeparator))
if (env.TryString("PSRULE_BINDING_NAMESEPARATOR", out var nameSeparator))
option.Binding.NameSeparator = nameSeparator;
if (env.TryBool("PSRULE_BINDING_PREFERTARGETINFO", out bool preferTargetInfo))
if (env.TryBool("PSRULE_BINDING_PREFERTARGETINFO", out var preferTargetInfo))
option.Binding.PreferTargetInfo = preferTargetInfo;
if (env.TryStringArray("PSRULE_BINDING_TARGETNAME", out string[] targetName))
if (env.TryStringArray("PSRULE_BINDING_TARGETNAME", out var targetName))
option.Binding.TargetName = targetName;
if (env.TryStringArray("PSRULE_BINDING_TARGETTYPE", out string[] targetType))
if (env.TryStringArray("PSRULE_BINDING_TARGETTYPE", out var targetType))
option.Binding.TargetType = targetType;
if (env.TryBool("PSRULE_BINDING_USEQUALIFIEDNAME", out bool useQualifiedName))
if (env.TryBool("PSRULE_BINDING_USEQUALIFIEDNAME", out var useQualifiedName))
option.Binding.UseQualifiedName = useQualifiedName;
if (env.TryString("PSRULE_RULE_BASELINE", out string baseline))
if (env.TryString("PSRULE_RULE_BASELINE", out var baseline))
option.Rule.Baseline = baseline;
if (env.TryStringArray("PSRULE_RULE_EXCLUDE", out string[] exclude))
if (env.TryStringArray("PSRULE_RULE_EXCLUDE", out var exclude))
option.Rule.Exclude = exclude;
if (env.TryBool("PSRULE_RULE_INCLUDELOCAL", out bool includeLocal))
if (env.TryBool("PSRULE_RULE_INCLUDELOCAL", out var includeLocal))
option.Rule.IncludeLocal = includeLocal;
if (env.TryStringArray("PSRULE_RULE_INCLUDE", out string[] include))
if (env.TryStringArray("PSRULE_RULE_INCLUDE", out var include))
option.Rule.Include = include;
// Rule.Tag - currently not supported
@ -114,34 +114,34 @@ namespace PSRule.Configuration
if (properties.TryPopValue("Binding.Field", out Hashtable map))
option.Binding.Field = new FieldMap(map);
if (properties.TryPopBool("Binding.IgnoreCase", out bool ignoreCase))
if (properties.TryPopBool("Binding.IgnoreCase", out var ignoreCase))
option.Binding.IgnoreCase = ignoreCase;
if (properties.TryPopString("Binding.NameSeparator", out string nameSeparator))
if (properties.TryPopString("Binding.NameSeparator", out var nameSeparator))
option.Binding.NameSeparator = nameSeparator;
if (properties.TryPopBool("Binding.PreferTargetInfo", out bool preferTargetInfo))
if (properties.TryPopBool("Binding.PreferTargetInfo", out var preferTargetInfo))
option.Binding.PreferTargetInfo = preferTargetInfo;
if (properties.TryPopStringArray("Binding.TargetName", out string[] targetName))
if (properties.TryPopStringArray("Binding.TargetName", out var targetName))
option.Binding.TargetName = targetName;
if (properties.TryPopStringArray("Binding.TargetType", out string[] targetType))
if (properties.TryPopStringArray("Binding.TargetType", out var targetType))
option.Binding.TargetType = targetType;
if (properties.TryPopValue("Binding.UseQualifiedName", out bool useQualifiedName))
option.Binding.UseQualifiedName = useQualifiedName;
if (properties.TryPopString("Rule.Baseline", out string baseline))
if (properties.TryPopString("Rule.Baseline", out var baseline))
option.Rule.Baseline = baseline;
if (properties.TryPopStringArray("Rule.Exclude", out string[] exclude))
if (properties.TryPopStringArray("Rule.Exclude", out var exclude))
option.Rule.Exclude = exclude;
if (properties.TryPopBool("Rule.IncludeLocal", out bool includeLocal))
if (properties.TryPopBool("Rule.IncludeLocal", out var includeLocal))
option.Rule.IncludeLocal = includeLocal;
if (properties.TryPopStringArray("Rule.Include", out string[] include))
if (properties.TryPopStringArray("Rule.Include", out var include))
option.Rule.Include = include;
if (properties.TryPopValue("Rule.Tag", out Hashtable tag))

Просмотреть файл

@ -70,7 +70,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Field != null ? Field.GetHashCode() : 0);
hash = hash * 23 + (IgnoreCase.HasValue ? IgnoreCase.Value.GetHashCode() : 0);
hash = hash * 23 + (NameSeparator != null ? NameSeparator.GetHashCode() : 0);

Просмотреть файл

@ -45,7 +45,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Include != null ? Include.GetHashCode() : 0);
return hash;
}
@ -65,13 +65,13 @@ namespace PSRule.Configuration
internal void Load(EnvironmentHelper env)
{
if (env.TryStringArray("PSRULE_CONVENTION_INCLUDE", out string[] include))
if (env.TryStringArray("PSRULE_CONVENTION_INCLUDE", out var include))
Include = include;
}
internal void Load(Dictionary<string, object> index)
{
if (index.TryPopStringArray("Convention.Include", out string[] include))
if (index.TryPopStringArray("Convention.Include", out var include))
Include = include;
}
}

Просмотреть файл

@ -62,7 +62,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (LanguageMode.HasValue ? LanguageMode.Value.GetHashCode() : 0);
hash = hash * 23 + (InconclusiveWarning.HasValue ? InconclusiveWarning.Value.GetHashCode() : 0);
hash = hash * 23 + (NotProcessedWarning.HasValue ? NotProcessedWarning.Value.GetHashCode() : 0);
@ -100,7 +100,7 @@ namespace PSRule.Configuration
if (env.TryEnum("PSRULE_EXECUTION_LANGUAGEMODE", out LanguageMode languageMode))
LanguageMode = languageMode;
if (env.TryBool("PSRULE_EXECUTION_INCONCLUSIVEWARNING", out bool bvalue))
if (env.TryBool("PSRULE_EXECUTION_INCONCLUSIVEWARNING", out var bvalue))
InconclusiveWarning = bvalue;
if (env.TryBool("PSRULE_EXECUTION_NOTPROCESSEDWARNING", out bvalue))
@ -115,7 +115,7 @@ namespace PSRule.Configuration
if (index.TryPopEnum("Execution.LanguageMode", out LanguageMode languageMode))
LanguageMode = languageMode;
if (index.TryPopBool("Execution.InconclusiveWarning", out bool bvalue))
if (index.TryPopBool("Execution.InconclusiveWarning", out var bvalue))
InconclusiveWarning = bvalue;
if (index.TryPopBool("Execution.NotProcessedWarning", out bvalue))

Просмотреть файл

@ -77,7 +77,7 @@ namespace PSRule.Configuration
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var found = TryField(binder.Name, out string[] value);
var found = TryField(binder.Name, out var value);
result = value;
return found;
}

Просмотреть файл

@ -52,7 +52,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Path != null ? Path.GetHashCode() : 0);
hash = hash * 23 + (Module != null ? Module.GetHashCode() : 0);
return hash;
@ -83,19 +83,19 @@ namespace PSRule.Configuration
internal void Load(EnvironmentHelper env)
{
if (env.TryStringArray("PSRULE_INCLUDE_PATH", out string[] path))
if (env.TryStringArray("PSRULE_INCLUDE_PATH", out var path))
Path = path;
if (env.TryStringArray("PSRULE_INCLUDE_MODULE", out string[] module))
if (env.TryStringArray("PSRULE_INCLUDE_MODULE", out var module))
Module = module;
}
internal void Load(Dictionary<string, object> index)
{
if (index.TryPopStringArray("Include.Path", out string[] path))
if (index.TryPopStringArray("Include.Path", out var path))
Path = path;
if (index.TryPopStringArray("Include.Module", out string[] module))
if (index.TryPopStringArray("Include.Module", out var module))
Module = module;
}
}

Просмотреть файл

@ -72,7 +72,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Format.HasValue ? Format.Value.GetHashCode() : 0);
hash = hash * 23 + (IgnoreGitPath.HasValue ? IgnoreGitPath.Value.GetHashCode() : 0);
hash = hash * 23 + (IgnoreRepositoryCommon.HasValue ? IgnoreRepositoryCommon.Value.GetHashCode() : 0);
@ -138,19 +138,19 @@ namespace PSRule.Configuration
if (env.TryEnum("PSRULE_INPUT_FORMAT", out InputFormat format))
Format = format;
if (env.TryBool("PSRULE_INPUT_IGNOREGITPATH", out bool ignoreGitPath))
if (env.TryBool("PSRULE_INPUT_IGNOREGITPATH", out var ignoreGitPath))
IgnoreGitPath = ignoreGitPath;
if (env.TryBool("PSRULE_INPUT_IGNOREREPOSITORYCOMMON", out bool ignoreRepositoryCommon))
if (env.TryBool("PSRULE_INPUT_IGNOREREPOSITORYCOMMON", out var ignoreRepositoryCommon))
IgnoreRepositoryCommon = ignoreRepositoryCommon;
if (env.TryString("PSRULE_INPUT_OBJECTPATH", out string objectPath))
if (env.TryString("PSRULE_INPUT_OBJECTPATH", out var objectPath))
ObjectPath = objectPath;
if (env.TryStringArray("PSRULE_INPUT_PATHIGNORE", out string[] pathIgnore))
if (env.TryStringArray("PSRULE_INPUT_PATHIGNORE", out var pathIgnore))
PathIgnore = pathIgnore;
if (env.TryStringArray("PSRULE_INPUT_TARGETTYPE", out string[] targetType))
if (env.TryStringArray("PSRULE_INPUT_TARGETTYPE", out var targetType))
TargetType = targetType;
}
@ -159,19 +159,19 @@ namespace PSRule.Configuration
if (index.TryPopEnum("Input.Format", out InputFormat format))
Format = format;
if (index.TryPopBool("Input.IgnoreGitPath", out bool ignoreGitPath))
if (index.TryPopBool("Input.IgnoreGitPath", out var ignoreGitPath))
IgnoreGitPath = ignoreGitPath;
if (index.TryPopBool("Input.IgnoreRepositoryCommon", out bool ignoreRepositoryCommon))
if (index.TryPopBool("Input.IgnoreRepositoryCommon", out var ignoreRepositoryCommon))
IgnoreRepositoryCommon = ignoreRepositoryCommon;
if (index.TryPopString("Input.ObjectPath", out string objectPath))
if (index.TryPopString("Input.ObjectPath", out var objectPath))
ObjectPath = objectPath;
if (index.TryPopStringArray("Input.PathIgnore", out string[] pathIgnore))
if (index.TryPopStringArray("Input.PathIgnore", out var pathIgnore))
PathIgnore = pathIgnore;
if (index.TryPopStringArray("Input.TargetType", out string[] targetType))
if (index.TryPopStringArray("Input.TargetType", out var targetType))
TargetType = targetType;
}
}

Просмотреть файл

@ -60,7 +60,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (LimitDebug != null ? LimitDebug.GetHashCode() : 0);
hash = hash * 23 + (LimitVerbose != null ? LimitVerbose.GetHashCode() : 0);
hash = hash * 23 + (RuleFail.HasValue ? RuleFail.Value.GetHashCode() : 0);
@ -107,10 +107,10 @@ namespace PSRule.Configuration
internal void Load(EnvironmentHelper env)
{
if (env.TryStringArray("PSRULE_LOGGING_LIMITDEBUG", out string[] limitDebug))
if (env.TryStringArray("PSRULE_LOGGING_LIMITDEBUG", out var limitDebug))
LimitDebug = limitDebug;
if (env.TryStringArray("PSRULE_LOGGING_LIMITVERBOSE", out string[] limitVerbose))
if (env.TryStringArray("PSRULE_LOGGING_LIMITVERBOSE", out var limitVerbose))
LimitVerbose = limitVerbose;
if (env.TryEnum("PSRULE_LOGGING_RULEFAIL", out OutcomeLogStream ruleFail))
@ -122,10 +122,10 @@ namespace PSRule.Configuration
internal void Load(Dictionary<string, object> index)
{
if (index.TryPopStringArray("Logging.LimitDebug", out string[] limitDebug))
if (index.TryPopStringArray("Logging.LimitDebug", out var limitDebug))
LimitDebug = limitDebug;
if (index.TryPopStringArray("Logging.LimitVerbose", out string[] limitVerbose))
if (index.TryPopStringArray("Logging.LimitVerbose", out var limitVerbose))
LimitVerbose = limitVerbose;
if (index.TryPopEnum("Logging.RuleFail", out OutcomeLogStream ruleFail))

Просмотреть файл

@ -88,7 +88,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (As.HasValue ? As.Value.GetHashCode() : 0);
hash = hash * 23 + (Banner.HasValue ? Banner.Value.GetHashCode() : 0);
hash = hash * 23 + (Culture != null ? Culture.GetHashCode() : 0);
@ -189,7 +189,7 @@ namespace PSRule.Configuration
if (env.TryEnum("PSRULE_OUTPUT_BANNER", out BannerFormat banner))
Banner = banner;
if (env.TryStringArray("PSRULE_OUTPUT_CULTURE", out string[] culture))
if (env.TryStringArray("PSRULE_OUTPUT_CULTURE", out var culture))
Culture = culture;
if (env.TryEnum("PSRULE_OUTPUT_ENCODING", out OutputEncoding encoding))
@ -204,13 +204,13 @@ namespace PSRule.Configuration
if (env.TryEnum("PSRULE_OUTPUT_OUTCOME", out RuleOutcome outcome))
Outcome = outcome;
if (env.TryString("PSRULE_OUTPUT_PATH", out string path))
if (env.TryString("PSRULE_OUTPUT_PATH", out var path))
Path = path;
if (env.TryEnum("PSRULE_OUTPUT_STYLE", out OutputStyle style))
Style = style;
if (env.TryInt("PSRULE_OUTPUT_JSONINDENT", out int jsonIndent))
if (env.TryInt("PSRULE_OUTPUT_JSONINDENT", out var jsonIndent))
JsonIndent = jsonIndent;
}
@ -222,7 +222,7 @@ namespace PSRule.Configuration
if (index.TryPopEnum("Output.Banner", out BannerFormat banner))
Banner = banner;
if (index.TryPopStringArray("Output.Culture", out string[] culture))
if (index.TryPopStringArray("Output.Culture", out var culture))
Culture = culture;
if (index.TryPopEnum("Output.Encoding", out OutputEncoding encoding))
@ -237,13 +237,13 @@ namespace PSRule.Configuration
if (index.TryPopEnum("Output.Outcome", out RuleOutcome outcome))
Outcome = outcome;
if (index.TryPopString("Output.Path", out string path))
if (index.TryPopString("Output.Path", out var path))
Path = path;
if (index.TryPopEnum("Output.Style", out OutputStyle style))
Style = style;
if (index.TryPopValue<int>("Output.JsonIndent", out int jsonIndent))
if (index.TryPopValue<int>("Output.JsonIndent", out var jsonIndent))
JsonIndent = jsonIndent;
}
}

Просмотреть файл

@ -151,16 +151,15 @@ namespace PSRule.Configuration
public string ToYaml()
{
var yaml = GetYaml();
if (string.IsNullOrEmpty(SourcePath))
{
return yaml;
}
return string.Concat(
string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.OptionsSourceComment, SourcePath),
Environment.NewLine,
yaml
);
return string.IsNullOrEmpty(SourcePath)
? yaml
: string.Concat(
string.Format(
Thread.CurrentThread.CurrentCulture,
PSRuleResources.OptionsSourceComment,
SourcePath),
Environment.NewLine,
yaml);
}
public PSRuleOption Clone()
@ -232,10 +231,7 @@ namespace PSRule.Configuration
var filePath = GetFilePath(path);
// Return empty options if file does not exist
if (!File.Exists(filePath))
return new PSRuleOption();
return FromEnvironment(FromYaml(path: filePath, yaml: File.ReadAllText(filePath)));
return !File.Exists(filePath) ? new PSRuleOption() : FromEnvironment(FromYaml(path: filePath, yaml: File.ReadAllText(filePath)));
}
/// <summary>
@ -395,7 +391,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Binding != null ? Binding.GetHashCode() : 0);
hash = hash * 23 + (Configuration != null ? Configuration.GetHashCode() : 0);
hash = hash * 23 + (Convention != null ? Convention.GetHashCode() : 0);
@ -422,7 +418,8 @@ namespace PSRule.Configuration
if (Path.HasExtension(rootedPath))
{
var ext = Path.GetExtension(rootedPath);
if (string.Equals(ext, ".yaml", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".yml", StringComparison.OrdinalIgnoreCase))
if (string.Equals(ext, ".yaml", StringComparison.OrdinalIgnoreCase) ||
string.Equals(ext, ".yml", StringComparison.OrdinalIgnoreCase))
{
return rootedPath;
}
@ -452,10 +449,9 @@ namespace PSRule.Configuration
internal static string GetRootedBasePath(string path)
{
var rootedPath = GetRootedPath(path);
if (rootedPath.Length > 0 && IsSeparator(rootedPath[rootedPath.Length - 1]))
return rootedPath;
return string.Concat(rootedPath, Path.DirectorySeparatorChar);
return rootedPath.Length > 0 && IsSeparator(rootedPath[rootedPath.Length - 1])
? rootedPath
: string.Concat(rootedPath, Path.DirectorySeparatorChar);
}
/// <summary>

Просмотреть файл

@ -56,7 +56,7 @@ namespace PSRule.Configuration
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Baseline != null ? Baseline.GetHashCode() : 0);
hash = hash * 23 + (Exclude != null ? Exclude.GetHashCode() : 0);
hash = hash * 23 + (IncludeLocal.HasValue ? IncludeLocal.Value.GetHashCode() : 0);

Просмотреть файл

@ -22,19 +22,13 @@ namespace PSRule.Data
{
get
{
if (_Index == null || !_Index.TryGetValue(type, out TargetSourceInfo value))
return null;
return value;
return _Index == null || !_Index.TryGetValue(type, out var value) ? null : value;
}
}
internal TargetSourceInfo[] GetSourceInfo()
{
if (_Items == null)
return Array.Empty<TargetSourceInfo>();
return _Items.ToArray();
return _Items == null ? Array.Empty<TargetSourceInfo>() : _Items.ToArray();
}
internal void AddRange(TargetSourceInfo[] sourceInfo)

Просмотреть файл

@ -38,7 +38,7 @@ namespace PSRule.Data
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Type != null ? Type.GetHashCode() : 0);
hash = hash * 23 + (Name != null ? Name.GetHashCode() : 0);
hash = hash * 23 + (Message != null ? Message.GetHashCode() : 0);
@ -48,10 +48,7 @@ namespace PSRule.Data
public static TargetIssueInfo Create(object o)
{
if (o is PSObject pso)
return Create(pso);
return null;
return o is PSObject pso ? Create(pso) : null;
}
public static TargetIssueInfo Create(PSObject o)

Просмотреть файл

@ -68,7 +68,7 @@ namespace PSRule.Data
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (File != null ? File.GetHashCode() : 0);
hash = hash * 23 + (Line.HasValue ? Line.Value.GetHashCode() : 0);
hash = hash * 23 + (Position.HasValue ? Position.Value.GetHashCode() : 0);
@ -86,15 +86,14 @@ namespace PSRule.Data
{
var type = Type ?? defaultType;
var file = useRelativePath ? ExpressionHelpers.NormalizePath(PSRuleOption.GetWorkingPath(), File) : File;
return string.IsNullOrEmpty(type) ? string.Concat(file, COLON, Line, COLON, Position) : string.Concat(type, COLONSPACE, file, COLON, Line, COLON, Position);
return string.IsNullOrEmpty(type)
? string.Concat(file, COLON, Line, COLON, Position)
: string.Concat(type, COLONSPACE, file, COLON, Line, COLON, Position);
}
public static TargetSourceInfo Create(object o)
{
if (o is PSObject pso)
return Create(pso);
return null;
return o is PSObject pso ? Create(pso) : null;
}
public static TargetSourceInfo Create(PSObject o)

Просмотреть файл

@ -80,10 +80,7 @@ namespace PSRule.Definitions.Baselines
private bool MatchWildcard(string name)
{
if (_WildcardMatch == null)
return false;
return _WildcardMatch.IsMatch(name);
return _WildcardMatch != null && _WildcardMatch.IsMatch(name);
}
}

Просмотреть файл

@ -34,18 +34,12 @@ namespace PSRule.Definitions.Conventions
public bool Match(IResource resource)
{
if (_Include == null)
return false;
return _Include.Contains(resource.Name) || _Include.Contains(resource.Id) || MatchWildcard(resource.Name) || MatchWildcard(resource.Id);
return _Include != null && (_Include.Contains(resource.Name) || _Include.Contains(resource.Id) || MatchWildcard(resource.Name) || MatchWildcard(resource.Id));
}
private bool MatchWildcard(string name)
{
if (_WildcardMatch == null)
return false;
return _WildcardMatch.IsMatch(name);
return _WildcardMatch != null && _WildcardMatch.IsMatch(name);
}
}

Просмотреть файл

@ -95,10 +95,7 @@ namespace PSRule.Definitions.Expressions
internal string[] GetReasons()
{
if (_Reason == null || _Reason.Count == 0)
return Array.Empty<string>();
return _Reason.ToArray();
return _Reason == null || _Reason.Count == 0 ? Array.Empty<string>() : _Reason.ToArray();
}
public RunspaceContext GetContext()

Просмотреть файл

@ -49,12 +49,12 @@ namespace PSRule.Definitions.Expressions
public bool IsOperator(string name)
{
return TryDescriptor(name, out ILanguageExpresssionDescriptor d) && d != null && d.Type == LanguageExpressionType.Operator;
return TryDescriptor(name, out var d) && d != null && d.Type == LanguageExpressionType.Operator;
}
public bool IsCondition(string name)
{
return TryDescriptor(name, out ILanguageExpresssionDescriptor d) && d != null && d.Type == LanguageExpressionType.Condition;
return TryDescriptor(name, out var d) && d != null && d.Type == LanguageExpressionType.Condition;
}
private void With(ILanguageExpresssionDescriptor descriptor)
@ -180,10 +180,7 @@ namespace PSRule.Definitions.Expressions
private LanguageExpressionOuterFn Debugger(LanguageExpressionOuterFn expression, string path)
{
if (!_Debugger)
return expression;
return (context, o) => DebuggerFn(context, path, expression, o);
return !_Debugger ? expression : ((context, o) => DebuggerFn(context, path, expression, o));
}
private static bool? DebuggerFn(ExpressionContext context, string path, LanguageExpressionOuterFn expression, object o)
@ -198,7 +195,10 @@ namespace PSRule.Definitions.Expressions
if (type == null)
return true;
var comparer = RunspaceContext.CurrentThread.Pipeline.Baseline.GetTargetBinding().IgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
var comparer = RunspaceContext.CurrentThread.Pipeline.Baseline.GetTargetBinding().IgnoreCase
? StringComparer.OrdinalIgnoreCase
: StringComparer.Ordinal;
var targetType = RunspaceContext.CurrentThread.RuleRecord.TargetType;
for (var i = 0; i < type.Length; i++)
{
@ -316,10 +316,7 @@ namespace PSRule.Definitions.Expressions
internal static bool If(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var inner = GetInner(args);
if (inner.Length > 0)
return inner[0](context, o) ?? true;
return false;
return inner.Length > 0 && (inner[0](context, o) ?? true);
}
internal static bool AnyOf(ExpressionContext context, ExpressionInfo info, object[] args, object o)
@ -347,10 +344,7 @@ namespace PSRule.Definitions.Expressions
internal static bool Not(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var inner = GetInner(args);
if (inner.Length > 0)
return !inner[0](context, o) ?? false;
return false;
return inner.Length > 0 && (!inner[0](context, o) ?? false);
}
#endregion Operators
@ -360,7 +354,7 @@ namespace PSRule.Definitions.Expressions
internal static bool Exists(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyBool(properties, EXISTS, out bool? propertyValue) && TryField(properties, out string field))
if (TryPropertyBool(properties, EXISTS, out var propertyValue) && TryField(properties, out var field))
{
context.ExpressionTrace(EXISTS, field, propertyValue);
return Condition(
@ -376,7 +370,7 @@ namespace PSRule.Definitions.Expressions
internal static bool Equals(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyAny(properties, EQUALS, out object propertyValue) || !TryOperand(context, EQUALS, o, properties, out IOperand operand))
if (!TryPropertyAny(properties, EQUALS, out var propertyValue) || !TryOperand(context, EQUALS, o, properties, out var operand))
return Invalid(context, EQUALS);
// int, string, bool
@ -392,13 +386,13 @@ namespace PSRule.Definitions.Expressions
internal static bool NotEquals(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyAny(properties, NOTEQUALS, out object propertyValue))
if (!TryPropertyAny(properties, NOTEQUALS, out var propertyValue))
return Invalid(context, NOTEQUALS);
if (TryFieldNotExists(context, o, properties))
return Pass();
if (!TryOperand(context, NOTEQUALS, o, properties, out IOperand operand))
if (!TryOperand(context, NOTEQUALS, o, properties, out var operand))
return Invalid(context, NOTEQUALS);
// int, string, bool
@ -414,14 +408,14 @@ namespace PSRule.Definitions.Expressions
internal static bool HasDefault(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyAny(properties, HASDEFAULT, out object propertyValue))
if (!TryPropertyAny(properties, HASDEFAULT, out var propertyValue))
return Invalid(context, HASDEFAULT);
GetCaseSensitive(properties, out bool caseSensitive);
GetCaseSensitive(properties, out var caseSensitive);
if (TryFieldNotExists(context, o, properties))
return Pass();
if (!TryOperand(context, HASDEFAULT, o, properties, out IOperand operand))
if (!TryOperand(context, HASDEFAULT, o, properties, out var operand))
return Invalid(context, HASDEFAULT);
return Condition(
@ -436,13 +430,13 @@ namespace PSRule.Definitions.Expressions
internal static bool HasValue(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyBool(properties, HASVALUE, out bool? propertyValue))
if (!TryPropertyBool(properties, HASVALUE, out var propertyValue))
return Invalid(context, HASVALUE);
if (TryFieldNotExists(context, o, properties) && !propertyValue.Value)
return Pass();
if (!TryOperand(context, HASVALUE, o, properties, out IOperand operand))
if (!TryOperand(context, HASVALUE, o, properties, out var operand))
return Invalid(context, HASVALUE);
return Condition(
@ -457,29 +451,28 @@ namespace PSRule.Definitions.Expressions
internal static bool Match(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyAny(properties, MATCH, out object propertyValue) || !TryOperand(context, MATCH, o, properties, out IOperand operand))
return Invalid(context, MATCH);
return Condition(
context,
ExpressionHelpers.Match(propertyValue, operand.Value, caseSensitive: false),
operand,
ReasonStrings.Assert_DoesNotMatch,
operand.Value,
propertyValue
);
return !TryPropertyAny(properties, MATCH, out var propertyValue) || !TryOperand(context, MATCH, o, properties, out var operand)
? Invalid(context, MATCH)
: Condition(
context,
ExpressionHelpers.Match(propertyValue, operand.Value, caseSensitive: false),
operand,
ReasonStrings.Assert_DoesNotMatch,
operand.Value,
propertyValue
);
}
internal static bool NotMatch(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyAny(properties, NOTMATCH, out object propertyValue))
if (!TryPropertyAny(properties, NOTMATCH, out var propertyValue))
return Invalid(context, NOTMATCH);
if (TryFieldNotExists(context, o, properties))
return Pass();
if (!TryOperand(context, NOTMATCH, o, properties, out IOperand operand))
if (!TryOperand(context, NOTMATCH, o, properties, out var operand))
return Invalid(context, NOTMATCH);
return Condition(
@ -495,7 +488,7 @@ namespace PSRule.Definitions.Expressions
internal static bool In(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyArray(properties, IN, out Array propertyValue) || !TryOperand(context, IN, o, properties, out IOperand operand))
if (!TryPropertyArray(properties, IN, out var propertyValue) || !TryOperand(context, IN, o, properties, out var operand))
return Invalid(context, IN);
for (var i = 0; propertyValue != null && i < propertyValue.Length; i++)
@ -514,13 +507,13 @@ namespace PSRule.Definitions.Expressions
internal static bool NotIn(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyArray(properties, NOTIN, out Array propertyValue))
if (!TryPropertyArray(properties, NOTIN, out var propertyValue))
return Invalid(context, NOTIN);
if (TryFieldNotExists(context, o, properties))
return Pass();
if (!TryOperand(context, NOTIN, o, properties, out IOperand operand))
if (!TryOperand(context, NOTIN, o, properties, out var operand))
return Invalid(context, NOTIN);
for (var i = 0; propertyValue != null && i < propertyValue.Length; i++)
@ -538,13 +531,15 @@ namespace PSRule.Definitions.Expressions
internal static bool SetOf(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyArray(properties, SETOF, out Array expectedValue) && TryField(properties, out string field) && GetCaseSensitive(properties, out bool caseSensitive))
if (TryPropertyArray(properties, SETOF, out var expectedValue) &&
TryField(properties, out var field) &&
GetCaseSensitive(properties, out var caseSensitive))
{
context.ExpressionTrace(SETOF, field, expectedValue);
if (!ObjectHelper.GetPath(context, o, field, caseSensitive: false, out object actualValue))
return NotHasField(context, field);
if (!ExpressionHelpers.TryEnumerableLength(actualValue, out int count))
if (!ExpressionHelpers.TryEnumerableLength(actualValue, out var count))
return Fail(context, ReasonStrings.NotEnumerable, field);
if (count != expectedValue.Length)
@ -563,8 +558,8 @@ namespace PSRule.Definitions.Expressions
internal static bool Subset(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyArray(properties, SUBSET, out Array expectedValue) && TryField(properties, out string field) &&
GetCaseSensitive(properties, out bool caseSensitive) && GetUnique(properties, out bool unique))
if (TryPropertyArray(properties, SUBSET, out var expectedValue) && TryField(properties, out var field) &&
GetCaseSensitive(properties, out var caseSensitive) && GetUnique(properties, out var unique))
{
context.ExpressionTrace(SUBSET, field, expectedValue);
if (!ObjectHelper.GetPath(context, o, field, caseSensitive: false, out object actualValue))
@ -575,8 +570,10 @@ namespace PSRule.Definitions.Expressions
for (var i = 0; expectedValue != null && i < expectedValue.Length; i++)
{
if (!ExpressionHelpers.CountValue(actualValue, expectedValue.GetValue(i), caseSensitive, out int count) || (count > 1 && unique))
return count == 0 ? Fail(context, ReasonStrings.Subset, field, expectedValue.GetValue(i)) : Fail(context, ReasonStrings.SubsetDuplicate, field, expectedValue.GetValue(i));
if (!ExpressionHelpers.CountValue(actualValue, expectedValue.GetValue(i), caseSensitive, out var count) || (count > 1 && unique))
return count == 0
? Fail(context, ReasonStrings.Subset, field, expectedValue.GetValue(i))
: Fail(context, ReasonStrings.SubsetDuplicate, field, expectedValue.GetValue(i));
}
return Pass();
}
@ -586,7 +583,7 @@ namespace PSRule.Definitions.Expressions
internal static bool Count(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyLong(properties, COUNT, out long? expectedValue) && TryField(properties, out string field))
if (TryPropertyLong(properties, COUNT, out var expectedValue) && TryField(properties, out var field))
{
context.ExpressionTrace(COUNT, field, expectedValue);
if (!ObjectHelper.GetPath(context, o, field, caseSensitive: false, out object value))
@ -595,7 +592,7 @@ namespace PSRule.Definitions.Expressions
if (value == null)
return Fail(context, ReasonStrings.Null, field);
if (ExpressionHelpers.TryEnumerableLength(value, value: out int actualValue))
if (ExpressionHelpers.TryEnumerableLength(value, value: out var actualValue))
return Condition(
context,
actualValue == expectedValue,
@ -611,7 +608,8 @@ namespace PSRule.Definitions.Expressions
internal static bool Less(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyLong(properties, LESS, out long? propertyValue) || !TryOperand(context, LESS, o, properties, out IOperand operand))
if (!TryPropertyLong(properties, LESS, out var propertyValue) ||
!TryOperand(context, LESS, o, properties, out var operand))
return Invalid(context, LESS);
if (operand.Value == null)
@ -622,7 +620,12 @@ namespace PSRule.Definitions.Expressions
ReasonStrings.Assert_IsNullOrEmpty
);
if (!ExpressionHelpers.CompareNumeric(operand.Value, propertyValue, convert: false, compare: out int compare, value: out _))
if (!ExpressionHelpers.CompareNumeric(
operand.Value,
propertyValue,
convert: false,
compare: out var compare,
value: out _))
return Invalid(context, LESS);
// int, string, bool
@ -640,7 +643,8 @@ namespace PSRule.Definitions.Expressions
internal static bool LessOrEquals(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyLong(properties, LESSOREQUALS, out long? propertyValue) || !TryOperand(context, LESSOREQUALS, o, properties, out IOperand operand))
if (!TryPropertyLong(properties, LESSOREQUALS, out var propertyValue) ||
!TryOperand(context, LESSOREQUALS, o, properties, out var operand))
return Invalid(context, LESSOREQUALS);
if (operand.Value == null)
@ -651,7 +655,12 @@ namespace PSRule.Definitions.Expressions
ReasonStrings.Assert_IsNullOrEmpty
);
if (!ExpressionHelpers.CompareNumeric(operand.Value, propertyValue, convert: false, compare: out int compare, value: out _))
if (!ExpressionHelpers.CompareNumeric(
operand.Value,
propertyValue,
convert: false,
compare: out var compare,
value: out _))
return Invalid(context, LESSOREQUALS);
// int, string, bool
@ -669,7 +678,8 @@ namespace PSRule.Definitions.Expressions
internal static bool Greater(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyLong(properties, GREATER, out long? propertyValue) || !TryOperand(context, GREATER, o, properties, out IOperand operand))
if (!TryPropertyLong(properties, GREATER, out var propertyValue) ||
!TryOperand(context, GREATER, o, properties, out var operand))
return Invalid(context, GREATER);
if (operand.Value == null)
@ -680,7 +690,12 @@ namespace PSRule.Definitions.Expressions
ReasonStrings.Assert_IsNullOrEmpty
);
if (!ExpressionHelpers.CompareNumeric(operand.Value, propertyValue, convert: false, compare: out int compare, value: out _))
if (!ExpressionHelpers.CompareNumeric(
operand.Value,
propertyValue,
convert: false,
compare: out var compare,
value: out _))
return Invalid(context, GREATER);
// int, string, bool
@ -698,7 +713,8 @@ namespace PSRule.Definitions.Expressions
internal static bool GreaterOrEquals(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (!TryPropertyLong(properties, GREATEROREQUALS, out long? propertyValue) || !TryOperand(context, GREATEROREQUALS, o, properties, out IOperand operand))
if (!TryPropertyLong(properties, GREATEROREQUALS, out var propertyValue) ||
!TryOperand(context, GREATEROREQUALS, o, properties, out var operand))
return Invalid(context, GREATEROREQUALS);
if (operand.Value == null)
@ -709,7 +725,12 @@ namespace PSRule.Definitions.Expressions
ReasonStrings.Assert_IsNullOrEmpty
);
if (!ExpressionHelpers.CompareNumeric(operand.Value, propertyValue, convert: false, compare: out int compare, value: out _))
if (!ExpressionHelpers.CompareNumeric(
operand.Value,
propertyValue,
convert: false,
compare: out var compare,
value: out _))
return Invalid(context, GREATEROREQUALS);
// int, string, bool
@ -727,10 +748,11 @@ namespace PSRule.Definitions.Expressions
internal static bool StartsWith(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyStringArray(properties, STARTSWITH, out string[] propertyValue) && TryOperand(context, STARTSWITH, o, properties, out IOperand operand))
if (TryPropertyStringArray(properties, STARTSWITH, out var propertyValue) &&
TryOperand(context, STARTSWITH, o, properties, out var operand))
{
context.ExpressionTrace(STARTSWITH, operand.Value, propertyValue);
if (!ExpressionHelpers.TryString(operand.Value, out string value))
if (!ExpressionHelpers.TryString(operand.Value, out var value))
return NotString(context, operand);
for (var i = 0; propertyValue != null && i < propertyValue.Length; i++)
@ -751,10 +773,11 @@ namespace PSRule.Definitions.Expressions
internal static bool EndsWith(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyStringArray(properties, ENDSWITH, out string[] propertyValue) && TryOperand(context, ENDSWITH, o, properties, out IOperand operand))
if (TryPropertyStringArray(properties, ENDSWITH, out var propertyValue) &&
TryOperand(context, ENDSWITH, o, properties, out var operand))
{
context.ExpressionTrace(ENDSWITH, operand.Value, propertyValue);
if (!ExpressionHelpers.TryString(operand.Value, out string value))
if (!ExpressionHelpers.TryString(operand.Value, out var value))
return NotString(context, operand);
for (var i = 0; propertyValue != null && i < propertyValue.Length; i++)
@ -775,10 +798,11 @@ namespace PSRule.Definitions.Expressions
internal static bool Contains(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyStringArray(properties, CONTAINS, out string[] propertyValue) && TryOperand(context, CONTAINS, o, properties, out IOperand operand))
if (TryPropertyStringArray(properties, CONTAINS, out var propertyValue) &&
TryOperand(context, CONTAINS, o, properties, out var operand))
{
context.ExpressionTrace(CONTAINS, operand.Value, propertyValue);
if (!ExpressionHelpers.TryString(operand.Value, out string value))
if (!ExpressionHelpers.TryString(operand.Value, out var value))
return NotString(context, operand);
for (var i = 0; propertyValue != null && i < propertyValue.Length; i++)
@ -799,7 +823,8 @@ namespace PSRule.Definitions.Expressions
internal static bool IsString(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyBool(properties, ISSTRING, out bool? propertyValue) && TryOperand(context, ISSTRING, o, properties, out IOperand operand))
if (TryPropertyBool(properties, ISSTRING, out var propertyValue) &&
TryOperand(context, ISSTRING, o, properties, out var operand))
{
context.ExpressionTrace(ISSTRING, operand.Value, propertyValue);
return Condition(
@ -816,9 +841,10 @@ namespace PSRule.Definitions.Expressions
internal static bool IsLower(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyBool(properties, ISLOWER, out bool? propertyValue) && TryOperand(context, ISLOWER, o, properties, out IOperand operand))
if (TryPropertyBool(properties, ISLOWER, out var propertyValue) &&
TryOperand(context, ISLOWER, o, properties, out var operand))
{
if (!ExpressionHelpers.TryString(operand.Value, out string value))
if (!ExpressionHelpers.TryString(operand.Value, out var value))
return Condition(
context,
!propertyValue.Value,
@ -842,9 +868,10 @@ namespace PSRule.Definitions.Expressions
internal static bool IsUpper(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyBool(properties, ISUPPER, out bool? propertyValue) && TryOperand(context, ISUPPER, o, properties, out IOperand operand))
if (TryPropertyBool(properties, ISUPPER, out var propertyValue) &&
TryOperand(context, ISUPPER, o, properties, out var operand))
{
if (!ExpressionHelpers.TryString(operand.Value, out string value))
if (!ExpressionHelpers.TryString(operand.Value, out var value))
return Condition(
context,
!propertyValue.Value,
@ -868,8 +895,8 @@ namespace PSRule.Definitions.Expressions
internal static bool HasSchema(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyArray(properties, HASSCHEMA, out Array expectedValue) && TryField(properties, out string field) &&
TryPropertyBoolOrDefault(properties, IGNORESCHEME, out bool ignoreScheme, false))
if (TryPropertyArray(properties, HASSCHEMA, out var expectedValue) && TryField(properties, out var field) &&
TryPropertyBoolOrDefault(properties, IGNORESCHEME, out var ignoreScheme, false))
{
context.ExpressionTrace(HASSCHEMA, field, expectedValue);
if (!ObjectHelper.GetPath(context, o, field, caseSensitive: false, out object actualValue))
@ -878,7 +905,7 @@ namespace PSRule.Definitions.Expressions
if (!ObjectHelper.GetPath(context, actualValue, PROPERTY_SCHEMA, caseSensitive: false, out object schemaValue))
return NotHasField(context, PROPERTY_SCHEMA);
if (!ExpressionHelpers.TryString(schemaValue, out string actualSchema))
if (!ExpressionHelpers.TryString(schemaValue, out var actualSchema))
return NotString(context, Operand.FromField(PROPERTY_SCHEMA, schemaValue));
if (string.IsNullOrEmpty(actualSchema))
@ -902,17 +929,18 @@ namespace PSRule.Definitions.Expressions
internal static bool Version(ExpressionContext context, ExpressionInfo info, object[] args, object o)
{
var properties = GetProperties(args);
if (TryPropertyString(properties, VERSION, out string expectedValue) && TryOperand(context, VERSION, o, properties, out IOperand operand) &&
TryPropertyBoolOrDefault(properties, INCLUDEPRERELEASE, out bool includePrerelease, false))
if (TryPropertyString(properties, VERSION, out var expectedValue) &&
TryOperand(context, VERSION, o, properties, out var operand) &&
TryPropertyBoolOrDefault(properties, INCLUDEPRERELEASE, out var includePrerelease, false))
{
context.ExpressionTrace(VERSION, operand.Value, expectedValue);
if (!ExpressionHelpers.TryString(operand.Value, out string version))
if (!ExpressionHelpers.TryString(operand.Value, out var version))
return NotString(context, operand);
if (!SemanticVersion.TryParseVersion(version, out SemanticVersion.Version actualVersion))
if (!SemanticVersion.TryParseVersion(version, out var actualVersion))
return Fail(context, operand, ReasonStrings.Version, operand.Value);
if (!SemanticVersion.TryParseConstraint(expectedValue, out SemanticVersion.IConstraint constraint, includePrerelease))
if (!SemanticVersion.TryParseConstraint(expectedValue, out var constraint, includePrerelease))
throw new RuleException(string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.VersionConstraintInvalid, expectedValue));
if (constraint != null && !constraint.Equals(actualVersion))
@ -1007,7 +1035,7 @@ namespace PSRule.Definitions.Expressions
private static bool TryPropertyBoolOrDefault(LanguageExpression.PropertyBag properties, string propertyName, out bool propertyValue, bool defaultValue)
{
propertyValue = defaultValue;
if (properties.TryGetBool(propertyName, out bool? value))
if (properties.TryGetBool(propertyName, out var value))
propertyValue = value.Value;
return true;
@ -1026,7 +1054,7 @@ namespace PSRule.Definitions.Expressions
private static bool TryField(IExpressionContext context, LanguageExpression.PropertyBag properties, object o, out IOperand operand)
{
operand = null;
if (!properties.TryGetString(FIELD, out string field))
if (!properties.TryGetString(FIELD, out var field))
return false;
if (ObjectHelper.GetPath(context, o, field, caseSensitive: false, out object value))
@ -1038,7 +1066,7 @@ namespace PSRule.Definitions.Expressions
private static bool TryName(IExpressionContext context, LanguageExpression.PropertyBag properties, out IOperand operand)
{
operand = null;
if (properties.TryGetString(NAME, out string svalue))
if (properties.TryGetString(NAME, out var svalue))
{
if (svalue != ".")
return Invalid(context, svalue);
@ -1056,7 +1084,7 @@ namespace PSRule.Definitions.Expressions
private static bool TryType(IExpressionContext context, LanguageExpression.PropertyBag properties, out IOperand operand)
{
operand = null;
if (properties.TryGetString(TYPE, out string svalue))
if (properties.TryGetString(TYPE, out var svalue))
{
if (svalue != ".")
return Invalid(context, svalue);
@ -1086,23 +1114,20 @@ namespace PSRule.Definitions.Expressions
/// </summary>
private static bool TryFieldNotExists(ExpressionContext context, object o, LanguageExpression.PropertyBag properties)
{
if (!properties.TryGetString(FIELD, out string field))
return false;
return !ObjectHelper.GetPath(context, o, field, caseSensitive: false, out object _);
return properties.TryGetString(FIELD, out var field) && !ObjectHelper.GetPath(context, o, field, caseSensitive: false, out object _);
}
private static bool TryOperand(ExpressionContext context, string name, object o, LanguageExpression.PropertyBag properties, out IOperand operand)
{
if (TryField(context, properties, o, out operand) || TryType(context, properties, out operand) || TryName(context, properties, out operand))
return true;
return Invalid(context, name);
return TryField(context, properties, o, out operand) ||
TryType(context, properties, out operand) ||
TryName(context, properties, out operand) ||
Invalid(context, name);
}
private static bool TryPropertyArray(LanguageExpression.PropertyBag properties, string propertyName, out Array propertyValue)
{
if (properties.TryGetValue(propertyName, out object array) && array is Array arrayValue)
if (properties.TryGetValue(propertyName, out var array) && array is Array arrayValue)
{
propertyValue = arrayValue;
return true;
@ -1117,7 +1142,7 @@ namespace PSRule.Definitions.Expressions
{
return true;
}
else if (properties.TryGetString(propertyName, out string s))
else if (properties.TryGetString(propertyName, out var s))
{
propertyValue = new string[] { s };
return true;

Просмотреть файл

@ -185,7 +185,7 @@ namespace PSRule.Definitions
if (key == null || value == null || !(key is string k) || !ContainsKey(k))
return false;
if (TryArray(value, out string[] values))
if (TryArray(value, out var values))
{
for (var i = 0; i < values.Length; i++)
{
@ -342,7 +342,7 @@ namespace PSRule.Definitions
TAnnotation IAnnotated<ResourceAnnotation>.GetAnnotation<TAnnotation>()
{
return _Annotations.TryGetValue(typeof(TAnnotation), out ResourceAnnotation annotation) ? (TAnnotation)annotation : null;
return _Annotations.TryGetValue(typeof(TAnnotation), out var annotation) ? (TAnnotation)annotation : null;
}
void IAnnotated<ResourceAnnotation>.SetAnnotation<TAnnotation>(TAnnotation annotation)
@ -419,10 +419,10 @@ namespace PSRule.Definitions
internal static bool IsObsolete(ResourceMetadata metadata)
{
if (metadata == null || metadata.Annotations == null || !metadata.Annotations.TryGetBool(ANNOTATION_OBSOLETE, out bool? obsolete))
return false;
return obsolete.GetValueOrDefault(false);
return metadata != null &&
metadata.Annotations != null &&
metadata.Annotations.TryGetBool(ANNOTATION_OBSOLETE, out var obsolete)
&& obsolete.GetValueOrDefault(false);
}
}
@ -435,10 +435,10 @@ namespace PSRule.Definitions
public override int GetHashCode(string obj)
{
ResourceHelper.ParseIdString(obj, out string scope, out string name);
ResourceHelper.ParseIdString(obj, out var scope, out var name);
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (scope != null ? scope.GetHashCode() : 0);
hash = hash * 23 + (name != null ? name.GetHashCode() : 0);
return hash;
@ -447,8 +447,8 @@ namespace PSRule.Definitions
public static bool IdEquals(string x, string y)
{
ResourceHelper.ParseIdString(x, out string scope_x, out string name_x);
ResourceHelper.ParseIdString(y, out string scope_y, out string name_y);
ResourceHelper.ParseIdString(x, out var scope_x, out var name_x);
ResourceHelper.ParseIdString(y, out var scope_y, out var name_y);
return EqualOrNull(scope_x, scope_y) &&
EqualOrNull(name_x, name_y);
}

Просмотреть файл

@ -49,7 +49,7 @@ namespace PSRule.Host
private DependencyTargetState State
{
get => Graph._State.TryGetValue(this, out DependencyTargetState state) ? state : DependencyTargetState.None;
get => Graph._State.TryGetValue(this, out var state) ? state : DependencyTargetState.None;
set => Graph._State[this] = value;
}

Просмотреть файл

@ -183,7 +183,7 @@ namespace PSRule.Host
context.VerboseRuleDiscovery(path: file.Path);
context.EnterSourceScope(source: file);
var scriptAst = System.Management.Automation.Language.Parser.ParseFile(file.Path, out Token[] tokens, out ParseError[] errors);
var scriptAst = System.Management.Automation.Language.Parser.ParseFile(file.Path, out var tokens, out var errors);
var visitor = new RuleLanguageAst(PipelineContext.CurrentThread);
scriptAst.Visit(visitor);
@ -662,21 +662,26 @@ namespace PSRule.Host
internal static RuleHelpInfo GetHelpInfo(RunspaceContext context, string name, string defaultSynopsis)
{
if (!TryHelpPath(context, name, out string path) || !TryDocument(path, out RuleDocument document))
return new RuleHelpInfo(name, name, context.Source.File.ModuleName)
return !TryHelpPath(context, name, out var path) || !TryDocument(path, out var document)
? new RuleHelpInfo(
name: name,
displayName: name,
moduleName: context.Source.File.ModuleName)
{
Synopsis = defaultSynopsis
}
: new RuleHelpInfo(
name: name,
displayName: document.Name ?? name,
moduleName: context.Source.File.ModuleName)
{
Synopsis = document.Synopsis?.Text ?? defaultSynopsis,
Description = document.Description?.Text,
Recommendation = document.Recommendation?.Text ?? document.Synopsis?.Text ?? defaultSynopsis,
Notes = document.Notes?.Text,
Links = GetLinks(document.Links),
Annotations = document.Annotations?.ToHashtable()
};
return new RuleHelpInfo(name: name, displayName: document.Name ?? name, moduleName: context.Source.File.ModuleName)
{
Synopsis = document.Synopsis?.Text ?? defaultSynopsis,
Description = document.Description?.Text,
Recommendation = document.Recommendation?.Text ?? document.Synopsis?.Text ?? defaultSynopsis,
Notes = document.Notes?.Text,
Links = GetLinks(document.Links),
Annotations = document.Annotations?.ToHashtable()
};
}
private static bool TryHelpPath(RunspaceContext context, string name, out string path)

Просмотреть файл

@ -46,7 +46,7 @@ namespace PSRule.Host
public bool Has<TAst>(string parameterName, out TAst parameterValue) where TAst : CommandElementAst
{
var result = Bound.TryGetValue(parameterName, out CommandElementAst value) && value is TAst;
var result = Bound.TryGetValue(parameterName, out var value) && value is TAst;
parameterValue = result ? value as TAst : null;
return result;
}
@ -59,7 +59,7 @@ namespace PSRule.Host
_Offset++;
return true;
}
int relative = position - _Offset;
var relative = position - _Offset;
var result = Unbound.Count > relative && Unbound[relative] is TAst;
value = result ? Unbound[relative] as TAst : null;
return result;
@ -151,8 +151,8 @@ namespace PSRule.Host
private static ParameterBindResult BindParameters(CommandAst commandAst)
{
var result = new ParameterBindResult();
int i = 1;
int next = 2;
var i = 1;
var next = 2;
for (; i < commandAst.CommandElements.Count; i++, next++)
{
// Is named parameter

Просмотреть файл

@ -23,7 +23,7 @@ namespace PSRule.Parser
return null;
// Check if the line is just dashes indicating start of yaml header
if (!stream.PeakLine(Dash, out int count) || count < 2)
if (!stream.PeakLine(Dash, out var count) || count < 2)
return null;
stream.Skip(count + 1);

Просмотреть файл

@ -89,7 +89,7 @@ namespace PSRule.Parser
return;
// Check if the line is just dashes indicating start of yaml header
if (!_Stream.PeakLine(Dash, out int count) || count < 2)
if (!_Stream.PeakLine(Dash, out var count) || count < 2)
return;
_Stream.Skip(count + 1);
@ -123,10 +123,10 @@ namespace PSRule.Parser
return false;
// Check the line is made up of the same characters
if (!_Stream.PeakLine(_Stream.Current, out int count))
if (!_Stream.PeakLine(_Stream.Current, out var count))
return false;
char currentChar = _Stream.Current;
var currentChar = _Stream.Current;
// Remove the previous token and replace with a header
if (_Output.Current?.Type == MarkdownTokenType.Text)
@ -327,18 +327,12 @@ namespace PSRule.Parser
var firstChar = clean[0];
if (firstChar == Dash || firstChar == Asterix)
return true;
return false;
return firstChar == Dash || firstChar == Asterix;
}
private static MarkdownTokens GetEnding(int lineEndings)
{
if (lineEndings == 0)
return MarkdownTokens.None;
return (lineEndings == 1) ? MarkdownTokens.LineEnding : MarkdownTokens.LineBreak;
return lineEndings == 0 ? MarkdownTokens.None : (lineEndings == 1) ? MarkdownTokens.LineEnding : MarkdownTokens.LineBreak;
}
/// <summary>

Просмотреть файл

@ -279,7 +279,7 @@ namespace PSRule.Parser
public int PeakCount(char c)
{
int count = 1;
var count = 1;
while (Peak(count) == c)
{
@ -305,7 +305,13 @@ namespace PSRule.Parser
return null;
}
var extent = new SourceExtent(_Source, null, _ExtentMarker.Value, _Position, _Line, _Column);
var extent = new SourceExtent(
source: _Source,
path: null,
start: _ExtentMarker.Value,
end: _Position,
line: _Line,
column: _Column);
_ExtentMarker = null;
@ -376,7 +382,14 @@ namespace PSRule.Parser
var next = _Source[position + 1];
// Check against list of escapable characters
if (next == Backslash || next == BracketOpen || next == ParenthesesOpen || next == AngleOpen || next == AngleClose || next == Backtick || next == BracketClose || next == ParenthesesClose)
if (next == Backslash ||
next == BracketOpen ||
next == ParenthesesOpen ||
next == AngleOpen ||
next == AngleClose ||
next == Backtick ||
next == BracketClose ||
next == ParenthesesClose)
{
return 1;
}

Просмотреть файл

@ -119,7 +119,11 @@ namespace PSRule.Parser
var links = new List<Link>();
stream.Next();
while (stream.IsTokenType(MarkdownTokenType.Link, MarkdownTokenType.LinkReference, MarkdownTokenType.LineBreak, MarkdownTokenType.Text))
while (stream.IsTokenType(
MarkdownTokenType.Link,
MarkdownTokenType.LinkReference,
MarkdownTokenType.LineBreak,
MarkdownTokenType.Text))
{
if (stream.IsTokenType(MarkdownTokenType.LineBreak) || stream.IsTokenType(MarkdownTokenType.Text))
{

Просмотреть файл

@ -171,30 +171,28 @@ namespace PSRule.Parser
public static IEnumerable<MarkdownToken> GetSection(this TokenStream stream, string header)
{
if (stream.Count == 0)
return Enumerable.Empty<MarkdownToken>();
return stream.Count == 0
? Enumerable.Empty<MarkdownToken>()
: stream
// Skip until we reach the header
.SkipWhile(token => token.Type != MarkdownTokenType.Header || token.Text != header)
return stream
// Skip until we reach the header
.SkipWhile(token => token.Type != MarkdownTokenType.Header || token.Text != header)
// Get all tokens to the next header
.Skip(1)
.TakeWhile(token => token.Type != MarkdownTokenType.Header);
// Get all tokens to the next header
.Skip(1)
.TakeWhile(token => token.Type != MarkdownTokenType.Header);
}
public static IEnumerable<MarkdownToken> GetSections(this TokenStream stream)
{
if (stream.Count == 0)
return Enumerable.Empty<MarkdownToken>();
return stream.Count == 0
? Enumerable.Empty<MarkdownToken>()
: stream
// Skip until we reach the header
.SkipWhile(token => token.Type != MarkdownTokenType.Header)
return stream
// Skip until we reach the header
.SkipWhile(token => token.Type != MarkdownTokenType.Header)
// Get all tokens to the next header
.Skip(1)
.TakeWhile(token => token.Type != MarkdownTokenType.Header);
// Get all tokens to the next header
.Skip(1)
.TakeWhile(token => token.Type != MarkdownTokenType.Header);
}
}
@ -233,13 +231,8 @@ namespace PSRule.Parser
public bool IsTokenType(params MarkdownTokenType[] tokenType)
{
if (Current == null || tokenType == null)
return false;
if (tokenType.Length == 1)
return tokenType[0] == Current.Type;
return tokenType.Contains(Current.Type);
return Current != null && tokenType != null &&
(tokenType.Length == 1 ? tokenType[0] == Current.Type : tokenType.Contains(Current.Type));
}
public MarkdownTokenType PeakTokenType(int offset = 1)
@ -326,10 +319,7 @@ namespace PSRule.Parser
public MarkdownToken ResolveLinkTarget(string name)
{
if (!_LinkTargetIndex.ContainsKey(name))
return null;
return _LinkTargetIndex[name];
return !_LinkTargetIndex.ContainsKey(name) ? null : _LinkTargetIndex[name];
}
public IEnumerator<MarkdownToken> GetEnumerator()

Просмотреть файл

@ -66,14 +66,27 @@ namespace PSRule.Pipeline
private static IAssertFormatter GetFormatter(OutputStyle style, Source[] source, PipelineWriter inner, PSRuleOption option)
{
switch (style)
if (style == OutputStyle.AzurePipelines)
{
case OutputStyle.AzurePipelines: return new AzurePipelinesFormatter(source, inner, option);
case OutputStyle.GitHubActions: return new GitHubActionsFormatter(source, inner, option);
case OutputStyle.VisualStudioCode: return new VisualStudioCodeFormatter(source, inner, option);
case OutputStyle.Plain: return new PlainFormatter(source, inner, option);
default: return new ClientFormatter(source, inner, option);
return new AzurePipelinesFormatter(source, inner, option);
}
if (style == OutputStyle.GitHubActions)
{
return new GitHubActionsFormatter(source, inner, option);
}
if (style == OutputStyle.VisualStudioCode)
{
return new VisualStudioCodeFormatter(source, inner, option);
}
if (style == OutputStyle.Plain)
{
return new PlainFormatter(source, inner, option);
}
return new ClientFormatter(source, inner, option);
}
private static OutputStyle GetStyle(OutputStyle style)
@ -225,7 +238,7 @@ namespace PSRule.Pipeline
if ((Option.Output.Outcome.Value & result.Outcome) != result.Outcome)
return;
StartResult(result, out RuleRecord[] records);
StartResult(result, out var records);
for (var i = 0; i < records.Length; i++)
{
if (records[i].IsSuccess())
@ -302,7 +315,18 @@ namespace PSRule.Pipeline
private void WriteStartResult(InvokeResult result)
{
WriteLine(string.Concat(GetTerminalSupport().StartResultIndent, result.TargetName, " : ", result.TargetType, " [", result.Pass, "/", result.Total, "]"), forgroundColor: GetTerminalSupport().StartResultForegroundColor);
WriteLine(
message: string.Concat(
GetTerminalSupport().StartResultIndent,
result.TargetName,
" : ",
result.TargetType,
" [",
result.Pass,
"/",
result.Total,
"]"),
forgroundColor: GetTerminalSupport().StartResultForegroundColor);
}
protected virtual TerminalSupport GetTerminalSupport()
@ -413,14 +437,25 @@ namespace PSRule.Pipeline
if (statusForeground != null || statusBackground != null)
{
Writer.WriteHost(new HostInformationMessage { Message = statusIndent, NoNewLine = true });
Writer.WriteHost(new HostInformationMessage { Message = status, ForegroundColor = statusForeground, BackgroundColor = statusBackground, NoNewLine = true });
Writer.WriteHost(new HostInformationMessage
{
Message = status,
ForegroundColor = statusForeground,
BackgroundColor = statusBackground,
NoNewLine = true
});
Writer.WriteHost(new HostInformationMessage { Message = " ", NoNewLine = true });
}
else
{
output = string.Concat(status, output);
}
Writer.WriteHost(new HostInformationMessage { Message = output, ForegroundColor = messageForeground, BackgroundColor = messageBackground });
Writer.WriteHost(new HostInformationMessage
{
Message = output,
ForegroundColor = messageForeground,
BackgroundColor = messageBackground
});
}
protected void WriteLine(string prefix, ConsoleColor? forgroundColor, string message, params object[] args)
@ -523,9 +558,9 @@ namespace PSRule.Pipeline
for (var i = 0; i < record.Source.Length; i++)
WriteIndentedLine(
record.Source[i].ToString(FormatterStrings.SourceAt, useRelativePath: true),
GetTerminalSupport().BodyIndent,
GetTerminalSupport().SourceLocationPrefix,
message: record.Source[i].ToString(FormatterStrings.SourceAt, useRelativePath: true),
indent: GetTerminalSupport().BodyIndent,
prefix: GetTerminalSupport().SourceLocationPrefix,
forgroundColor: GetTerminalSupport().SourceLocationForegroundColor
);
}
@ -539,9 +574,9 @@ namespace PSRule.Pipeline
LineBreak();
WriteIndentedLine(
record.Info.Synopsis,
GetTerminalSupport().BodyIndent,
GetTerminalSupport().SynopsisPrefix,
message: record.Info.Synopsis,
indent: GetTerminalSupport().BodyIndent,
prefix: GetTerminalSupport().SynopsisPrefix,
forgroundColor: GetTerminalSupport().SynopsisForegroundColor
);
}
@ -554,9 +589,9 @@ namespace PSRule.Pipeline
LineBreak();
WriteLine(GetTerminalSupport().RecommendationHeading, forgroundColor: GetTerminalSupport().BodyForegroundColor);
WriteIndentedLines(
record.Recommendation,
GetTerminalSupport().BodyIndent,
GetTerminalSupport().RecommendationPrefix,
message: record.Recommendation,
indent: GetTerminalSupport().BodyIndent,
prefix: GetTerminalSupport().RecommendationPrefix,
forgroundColor: GetTerminalSupport().BodyForegroundColor
);
}
@ -571,9 +606,9 @@ namespace PSRule.Pipeline
for (var i = 0; i < record.Reason.Length; i++)
{
WriteIndentedLine(
record.Reason[i],
GetTerminalSupport().BodyIndent,
GetTerminalSupport().ReasonItemPrefix,
message: record.Reason[i],
indent: GetTerminalSupport().BodyIndent,
prefix: GetTerminalSupport().ReasonItemPrefix,
forgroundColor: GetTerminalSupport().BodyForegroundColor
);
}
@ -588,9 +623,9 @@ namespace PSRule.Pipeline
LineBreak();
WriteLine(GetTerminalSupport().HelpHeading, forgroundColor: GetTerminalSupport().BodyForegroundColor);
WriteIndentedLine(
link,
GetTerminalSupport().BodyIndent,
GetTerminalSupport().HelpLinkPrefix,
message: link,
indent: GetTerminalSupport().BodyIndent,
prefix: GetTerminalSupport().HelpLinkPrefix,
forgroundColor: GetTerminalSupport().BodyForegroundColor
);
}
@ -600,7 +635,14 @@ namespace PSRule.Pipeline
{
BreakIfUnbrokenObject();
BreakIfUnbrokenContent();
WriteStatus(GetTerminalSupport().ErrorStatus, indent, GetTerminalSupport().ErrorStatusForegroundColor, GetTerminalSupport().ErrorStatusBackgroundColor, GetTerminalSupport().ErrorForegroundColor, GetTerminalSupport().ErrorBackgroundColor, message);
WriteStatus(
status: GetTerminalSupport().ErrorStatus,
statusIndent: indent,
statusForeground: GetTerminalSupport().ErrorStatusForegroundColor,
statusBackground: GetTerminalSupport().ErrorStatusBackgroundColor,
messageForeground: GetTerminalSupport().ErrorForegroundColor,
messageBackground: GetTerminalSupport().ErrorBackgroundColor,
message: message);
UnbrokenInfo();
}
@ -608,7 +650,14 @@ namespace PSRule.Pipeline
{
BreakIfUnbrokenObject();
BreakIfUnbrokenContent();
WriteStatus(GetTerminalSupport().WarningStatus, indent, GetTerminalSupport().WarningStatusForegroundColor, GetTerminalSupport().WarningStatusBackgroundColor, GetTerminalSupport().WarningForegroundColor, GetTerminalSupport().WarningBackgroundColor, message);
WriteStatus(
status: GetTerminalSupport().WarningStatus,
statusIndent: indent,
statusForeground: GetTerminalSupport().WarningStatusForegroundColor,
statusBackground: GetTerminalSupport().WarningStatusBackgroundColor,
messageForeground: GetTerminalSupport().WarningForegroundColor,
messageBackground: GetTerminalSupport().WarningBackgroundColor,
message: message);
UnbrokenInfo();
}
@ -616,7 +665,14 @@ namespace PSRule.Pipeline
{
BreakIfUnbrokenObject();
BreakIfUnbrokenInfo();
WriteStatus(GetTerminalSupport().PassStatus, GetTerminalSupport().BodyIndent, GetTerminalSupport().PassStatusForegroundColor, GetTerminalSupport().PassStatusBackgroundColor, GetTerminalSupport().PassForegroundColor, GetTerminalSupport().PassBackgroundColor, record.RuleName);
WriteStatus(
status: GetTerminalSupport().PassStatus,
statusIndent: GetTerminalSupport().BodyIndent,
statusForeground: GetTerminalSupport().PassStatusForegroundColor,
statusBackground: GetTerminalSupport().PassStatusBackgroundColor,
messageForeground: GetTerminalSupport().PassForegroundColor,
messageBackground: GetTerminalSupport().PassBackgroundColor,
message: record.RuleName);
UnbrokenContent();
}
@ -624,7 +680,14 @@ namespace PSRule.Pipeline
{
BreakIfUnbrokenObject();
BreakIfUnbrokenInfo();
WriteStatus(GetTerminalSupport().FailStatus, GetTerminalSupport().BodyIndent, GetTerminalSupport().FailStatusForegroundColor, GetTerminalSupport().FailStatusBackgroundColor, GetTerminalSupport().FailForegroundColor, GetTerminalSupport().FailBackgroundColor, record.RuleName);
WriteStatus(
status: GetTerminalSupport().FailStatus,
statusIndent: GetTerminalSupport().BodyIndent,
statusForeground: GetTerminalSupport().FailStatusForegroundColor,
statusBackground: GetTerminalSupport().FailStatusBackgroundColor,
messageForeground: GetTerminalSupport().FailForegroundColor,
messageBackground: GetTerminalSupport().FailBackgroundColor,
message: record.RuleName);
FailDetail(record);
}
@ -632,7 +695,14 @@ namespace PSRule.Pipeline
{
BreakIfUnbrokenObject();
BreakIfUnbrokenInfo();
WriteStatus(GetTerminalSupport().ErrorStatus, GetTerminalSupport().BodyIndent, GetTerminalSupport().ErrorStatusForegroundColor, GetTerminalSupport().ErrorStatusBackgroundColor, GetTerminalSupport().ErrorForegroundColor, GetTerminalSupport().ErrorBackgroundColor, record.RuleName);
WriteStatus(
status: GetTerminalSupport().ErrorStatus,
statusIndent: GetTerminalSupport().BodyIndent,
statusForeground: GetTerminalSupport().ErrorStatusForegroundColor,
statusBackground: GetTerminalSupport().ErrorStatusBackgroundColor,
messageForeground: GetTerminalSupport().ErrorForegroundColor,
messageBackground: GetTerminalSupport().ErrorBackgroundColor,
message: record.RuleName);
ErrorDetail(record);
UnbrokenContent();
}
@ -750,7 +820,12 @@ namespace PSRule.Pipeline
return;
LineBreak();
Error(string.Format(Thread.CurrentThread.CurrentCulture, FormatterStrings.Result_ErrorDetail, record.TargetName, record.RuleName, record.Error.Message));
Error(string.Format(
Thread.CurrentThread.CurrentCulture,
FormatterStrings.Result_ErrorDetail,
record.TargetName,
record.RuleName,
record.Error.Message));
LineBreak();
WriteLine(record.Error.PositionMessage);
LineBreak();
@ -760,7 +835,12 @@ namespace PSRule.Pipeline
protected override void FailDetail(RuleRecord record)
{
base.FailDetail(record);
Error(string.Format(Thread.CurrentThread.CurrentCulture, FormatterStrings.Result_FailDetail, record.TargetName, record.RuleName, record.Info.Synopsis));
Error(string.Format(
Thread.CurrentThread.CurrentCulture,
FormatterStrings.Result_FailDetail,
record.TargetName,
record.RuleName,
record.Info.Synopsis));
LineBreak();
}
}
@ -797,7 +877,12 @@ namespace PSRule.Pipeline
return;
LineBreak();
Error(string.Format(Thread.CurrentThread.CurrentCulture, FormatterStrings.Result_ErrorDetail, record.TargetName, record.RuleName, record.Error.Message));
Error(string.Format(
Thread.CurrentThread.CurrentCulture,
FormatterStrings.Result_ErrorDetail,
record.TargetName,
record.RuleName,
record.Error.Message));
LineBreak();
WriteLine(record.Error.PositionMessage);
LineBreak();
@ -807,7 +892,12 @@ namespace PSRule.Pipeline
protected override void FailDetail(RuleRecord record)
{
base.FailDetail(record);
Error(string.Format(Thread.CurrentThread.CurrentCulture, FormatterStrings.Result_FailDetail, record.TargetName, record.RuleName, record.Info.Synopsis));
Error(string.Format(
Thread.CurrentThread.CurrentCulture,
FormatterStrings.Result_FailDetail,
record.TargetName,
record.RuleName,
record.Info.Synopsis));
LineBreak();
}
}
@ -914,11 +1004,23 @@ namespace PSRule.Pipeline
try
{
if (_ErrorCount > 0)
base.WriteError(new ErrorRecord(new FailPipelineException(PSRuleResources.RuleErrorPipelineException), "PSRule.Error", ErrorCategory.InvalidOperation, null));
base.WriteError(new ErrorRecord(
new FailPipelineException(PSRuleResources.RuleErrorPipelineException),
"PSRule.Error",
ErrorCategory.InvalidOperation,
null));
else if (_FailCount > 0)
base.WriteError(new ErrorRecord(new FailPipelineException(PSRuleResources.RuleFailPipelineException), "PSRule.Fail", ErrorCategory.InvalidData, null));
base.WriteError(new ErrorRecord(
new FailPipelineException(PSRuleResources.RuleFailPipelineException),
"PSRule.Fail",
ErrorCategory.InvalidData,
null));
else if (_PSError)
base.WriteError(new ErrorRecord(new FailPipelineException(PSRuleResources.ErrorPipelineException), "PSRule.Error", ErrorCategory.InvalidOperation, null));
base.WriteError(new ErrorRecord(
new FailPipelineException(PSRuleResources.ErrorPipelineException),
"PSRule.Error",
ErrorCategory.InvalidOperation,
null));
if (_Results != null && _CmdletContext != null)
_CmdletContext.SessionState.PSVariable.Set(_ResultVariableName, _Results.ToArray());
@ -952,14 +1054,14 @@ namespace PSRule.Pipeline
{
var next = ShouldOutput() ? base.PrepareWriter() : null;
_Writer = new AssertWriter(
Option,
Source,
GetOutput(),
next,
Option.Output.Style ?? OutputOption.Default.Style.Value,
_ResultVariableName,
HostContext.CmdletContext,
HostContext.ExecutionContext
option: Option,
source: Source,
inner: GetOutput(),
next: next,
style: Option.Output.Style ?? OutputOption.Default.Style.Value,
resultVariableName: _ResultVariableName,
cmdletContext: HostContext.CmdletContext,
executionContext: HostContext.ExecutionContext
);
}
return _Writer;
@ -974,10 +1076,16 @@ namespace PSRule.Pipeline
public sealed override IPipeline Build(IPipelineWriter writer = null)
{
if (!RequireModules() || !RequireSources())
return null;
return new InvokeRulePipeline(PrepareContext(BindTargetNameHook, BindTargetTypeHook, BindFieldHook), Source, writer ?? PrepareWriter(), RuleOutcome.Processed);
return !RequireModules() || !RequireSources()
? null
: (IPipeline)new InvokeRulePipeline(
context: PrepareContext(
bindTargetName: BindTargetNameHook,
bindTargetType: BindTargetTypeHook,
bindField: BindFieldHook),
source: Source,
writer: writer ?? PrepareWriter(),
outcome: RuleOutcome.Processed);
}
}
}

Просмотреть файл

@ -52,7 +52,14 @@ namespace PSRule.Pipeline
public override IPipeline Build(IPipelineWriter writer = null)
{
return new GetRuleHelpPipeline(PrepareContext(null, null, null), Source, PrepareReader(), writer ?? PrepareWriter());
return new GetRuleHelpPipeline(
pipeline: PrepareContext(
bindTargetName: null,
bindTargetType: null,
bindField: null),
source: Source,
reader: PrepareReader(),
writer: writer ?? PrepareWriter());
}
private sealed class HelpWriter : PipelineWriter

Просмотреть файл

@ -43,20 +43,19 @@ namespace PSRule.Pipeline
public override IPipeline Build(IPipelineWriter writer = null)
{
if (!RequireModules() || !RequireSources())
return null;
return new GetRulePipeline(
pipeline: PrepareContext(
bindTargetName: null,
bindTargetType: null,
bindField: null
),
source: Source,
reader: PrepareReader(),
writer: writer ?? PrepareWriter(),
includeDependencies: _IncludeDependencies
);
return !RequireModules() || !RequireSources()
? null
: (IPipeline)new GetRulePipeline(
pipeline: PrepareContext(
bindTargetName: null,
bindTargetType: null,
bindField: null
),
source: Source,
reader: PrepareReader(),
writer: writer ?? PrepareWriter(),
includeDependencies: _IncludeDependencies
);
}
private static OutputFormat SuppressFormat(OutputFormat? format)

Просмотреть файл

@ -133,7 +133,7 @@ namespace PSRule.Pipeline
try
{
Reader.Enqueue(sourceObject);
while (Reader.TryDequeue(out TargetObject next))
while (Reader.TryDequeue(out var next))
Writer.WriteObject(next.Value, false);
}
catch (Exception)

Просмотреть файл

@ -72,26 +72,19 @@ namespace PSRule.Pipeline
public ActionPreference GetPreferenceVariable(string variableName)
{
if (ExecutionContext == null)
return ActionPreference.SilentlyContinue;
return (ActionPreference)ExecutionContext.SessionState.PSVariable.GetValue(variableName);
return ExecutionContext == null
? ActionPreference.SilentlyContinue
: (ActionPreference)ExecutionContext.SessionState.PSVariable.GetValue(variableName);
}
public T GetVariable<T>(string variableName)
{
if (ExecutionContext == null)
return default;
return (T)ExecutionContext.SessionState.PSVariable.GetValue(variableName);
return ExecutionContext == null ? default : (T)ExecutionContext.SessionState.PSVariable.GetValue(variableName);
}
public bool ShouldProcess(string target, string action)
{
if (CmdletContext == null)
return true;
return CmdletContext.ShouldProcess(target, action);
return CmdletContext == null || CmdletContext.ShouldProcess(target, action);
}
}
}

Просмотреть файл

@ -46,10 +46,7 @@ namespace PSRule.Pipeline
{
get
{
if (_Record == null || _Record.Count == 0)
return null;
return _Record[0].TargetName;
return IsEmptyRecord() ? null : _Record[0].TargetName;
}
}
@ -57,13 +54,15 @@ namespace PSRule.Pipeline
{
get
{
if (_Record == null || _Record.Count == 0)
return null;
return _Record[0].TargetType;
return IsEmptyRecord() ? null : _Record[0].TargetType;
}
}
private bool IsEmptyRecord()
{
return _Record == null || _Record.Count == 0;
}
/// <summary>
/// Get the individual records for the target object.
/// </summary>

Просмотреть файл

@ -91,10 +91,9 @@ namespace PSRule.Pipeline
public override IPipeline Build(IPipelineWriter writer = null)
{
if (!RequireModules() || !RequireSources())
return null;
return new InvokeRulePipeline(PrepareContext(BindTargetNameHook, BindTargetTypeHook, BindFieldHook), Source, writer ?? PrepareWriter(), Option.Output.Outcome.Value);
return !RequireModules() || !RequireSources()
? null
: (IPipeline)new InvokeRulePipeline(PrepareContext(BindTargetNameHook, BindTargetTypeHook, BindFieldHook), Source, writer ?? PrepareWriter(), Option.Output.Outcome.Value);
}
protected override PipelineReader PrepareReader()
@ -199,7 +198,7 @@ namespace PSRule.Pipeline
try
{
Reader.Enqueue(sourceObject);
while (Reader.TryDequeue(out TargetObject next))
while (Reader.TryDequeue(out var next))
{
var result = ProcessTargetObject(next);
_Completed.Add(result);
@ -315,7 +314,7 @@ namespace PSRule.Pipeline
/// </summary>
private void AddToSummary(RuleBlock ruleBlock, RuleOutcome outcome)
{
if (!_Summary.TryGetValue(ruleBlock.RuleId, out RuleSummaryRecord s))
if (!_Summary.TryGetValue(ruleBlock.RuleId, out var s))
{
s = new RuleSummaryRecord(
ruleId: ruleBlock.RuleId,

Просмотреть файл

@ -122,8 +122,9 @@ namespace PSRule.Pipeline
Include = option.Rule?.Include;
Exclude = option.Rule?.Exclude;
Tag = option.Rule?.Tag;
Configuration = option.Configuration != null ?
new Dictionary<string, object>(option.Configuration, StringComparer.OrdinalIgnoreCase) : new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Configuration = option.Configuration != null
? new Dictionary<string, object>(option.Configuration, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Convention = new ConventionOption(option.Convention);
}
@ -170,8 +171,9 @@ namespace PSRule.Pipeline
TargetType = option.Binding?.TargetType;
UseQualifiedName = option.Binding?.UseQualifiedName;
Culture = option.Output?.Culture;
Configuration = option.Configuration != null ?
new Dictionary<string, object>(option.Configuration, StringComparer.OrdinalIgnoreCase) : new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Configuration = option.Configuration != null
? new Dictionary<string, object>(option.Configuration, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Convention = new ConventionOption(option.Convention);
}
@ -186,8 +188,9 @@ namespace PSRule.Pipeline
TargetType = spec.Binding?.TargetType;
UseQualifiedName = spec.Binding?.UseQualifiedName;
Culture = spec.Output?.Culture;
Configuration = spec.Configuration != null ?
new Dictionary<string, object>(spec.Configuration, StringComparer.OrdinalIgnoreCase) : new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Configuration = spec.Configuration != null
? new Dictionary<string, object>(spec.Configuration, StringComparer.OrdinalIgnoreCase)
: new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
Convention = new ConventionOption(spec.Convention);
}
}
@ -240,7 +243,7 @@ namespace PSRule.Pipeline
{
unchecked // Overflow is fine
{
int hash = 17;
var hash = 17;
hash = hash * 23 + (Field != null ? Field.GetHashCode() : 0);
hash = hash * 23 + (IgnoreCase ? IgnoreCase.GetHashCode() : 0);
hash = hash * 23 + (NameSeparator != null ? NameSeparator.GetHashCode() : 0);
@ -260,8 +263,8 @@ namespace PSRule.Pipeline
public void UseScope(string moduleName)
{
_ModuleConfig = !string.IsNullOrEmpty(moduleName) && _ModuleConfigScope.TryGetValue(moduleName, out ConfigScope configScope) ? configScope : null;
_ModuleBaseline = !string.IsNullOrEmpty(moduleName) && _ModuleBaselineScope.TryGetValue(moduleName, out BaselineScope baselineScope) ? baselineScope : null;
_ModuleConfig = !string.IsNullOrEmpty(moduleName) && _ModuleConfigScope.TryGetValue(moduleName, out var configScope) ? configScope : null;
_ModuleBaseline = !string.IsNullOrEmpty(moduleName) && _ModuleBaselineScope.TryGetValue(moduleName, out var baselineScope) ? baselineScope : null;
_Binding = null;
_Configuration = null;
_Filter = null;
@ -274,10 +277,10 @@ namespace PSRule.Pipeline
if (_Filter != null)
return _Filter;
string[] include = _Parameter?.Include ?? _Explicit?.Include ?? _WorkspaceBaseline?.Include ?? _ModuleBaseline?.Include;
string[] exclude = _Explicit?.Exclude ?? _WorkspaceBaseline?.Exclude ?? _ModuleBaseline?.Exclude;
Hashtable tag = _Parameter?.Tag ?? _Explicit?.Tag ?? _WorkspaceBaseline?.Tag ?? _ModuleBaseline?.Tag;
bool? includeLocal = _Explicit?.IncludeLocal ?? _WorkspaceBaseline?.IncludeLocal ?? _ModuleBaseline?.IncludeLocal;
var include = _Parameter?.Include ?? _Explicit?.Include ?? _WorkspaceBaseline?.Include ?? _ModuleBaseline?.Include;
var exclude = _Explicit?.Exclude ?? _WorkspaceBaseline?.Exclude ?? _ModuleBaseline?.Exclude;
var tag = _Parameter?.Tag ?? _Explicit?.Tag ?? _WorkspaceBaseline?.Tag ?? _ModuleBaseline?.Tag;
var includeLocal = _Explicit?.IncludeLocal ?? _WorkspaceBaseline?.IncludeLocal ?? _ModuleBaseline?.IncludeLocal;
return _Filter = new RuleFilter(include, tag, exclude, includeLocal);
}
@ -305,29 +308,23 @@ namespace PSRule.Pipeline
return _Binding;
var field = new FieldMap[] { _Explicit?.Field, _WorkspaceBaseline?.Field, _ModuleBaseline?.Field, _ModuleConfig?.Field };
bool ignoreCase = _Explicit?.IgnoreCase ?? _WorkspaceBaseline?.IgnoreCase ?? _ModuleBaseline?.IgnoreCase ?? _ModuleConfig?.IgnoreCase ?? Configuration.BindingOption.Default.IgnoreCase.Value;
string nameSeparator = _Explicit?.NameSeparator ?? _WorkspaceBaseline?.NameSeparator ?? _ModuleBaseline?.NameSeparator ?? _ModuleConfig?.NameSeparator ?? Configuration.BindingOption.Default.NameSeparator;
bool preferTargetInfo = _Explicit?.PreferTargetInfo ?? _WorkspaceBaseline?.PreferTargetInfo ?? _ModuleBaseline?.PreferTargetInfo ?? _ModuleConfig?.PreferTargetInfo ?? Configuration.BindingOption.Default.PreferTargetInfo.Value;
string[] targetName = _Explicit?.TargetName ?? _WorkspaceBaseline?.TargetName ?? _ModuleBaseline?.TargetName ?? _ModuleConfig?.TargetName;
string[] targetType = _Explicit?.TargetType ?? _WorkspaceBaseline?.TargetType ?? _ModuleBaseline?.TargetType ?? _ModuleConfig?.TargetType;
bool useQualifiedName = _Explicit?.UseQualifiedName ?? _WorkspaceBaseline?.UseQualifiedName ?? _ModuleBaseline?.UseQualifiedName ?? _ModuleConfig?.UseQualifiedName ?? Configuration.BindingOption.Default.UseQualifiedName.Value;
var ignoreCase = _Explicit?.IgnoreCase ?? _WorkspaceBaseline?.IgnoreCase ?? _ModuleBaseline?.IgnoreCase ?? _ModuleConfig?.IgnoreCase ?? Configuration.BindingOption.Default.IgnoreCase.Value;
var nameSeparator = _Explicit?.NameSeparator ?? _WorkspaceBaseline?.NameSeparator ?? _ModuleBaseline?.NameSeparator ?? _ModuleConfig?.NameSeparator ?? Configuration.BindingOption.Default.NameSeparator;
var preferTargetInfo = _Explicit?.PreferTargetInfo ?? _WorkspaceBaseline?.PreferTargetInfo ?? _ModuleBaseline?.PreferTargetInfo ?? _ModuleConfig?.PreferTargetInfo ?? Configuration.BindingOption.Default.PreferTargetInfo.Value;
var targetName = _Explicit?.TargetName ?? _WorkspaceBaseline?.TargetName ?? _ModuleBaseline?.TargetName ?? _ModuleConfig?.TargetName;
var targetType = _Explicit?.TargetType ?? _WorkspaceBaseline?.TargetType ?? _ModuleBaseline?.TargetType ?? _ModuleConfig?.TargetType;
var useQualifiedName = _Explicit?.UseQualifiedName ?? _WorkspaceBaseline?.UseQualifiedName ?? _ModuleBaseline?.UseQualifiedName ?? _ModuleConfig?.UseQualifiedName ?? Configuration.BindingOption.Default.UseQualifiedName.Value;
return _Binding = new BindingOption(field, ignoreCase, preferTargetInfo, nameSeparator, targetName, targetType, useQualifiedName);
}
public Dictionary<string, object> GetConfiguration()
{
if (_Configuration != null)
return _Configuration;
return _Configuration = AddConfiguration();
return _Configuration ??= AddConfiguration();
}
public string[] GetCulture()
{
if (_Culture != null)
return _Culture;
return _Culture = _WorkspaceConfig?.Culture ?? _ModuleConfig?.Culture ?? _DefaultCulture;
return _Culture ??= _WorkspaceConfig?.Culture ?? _ModuleConfig?.Culture ?? _DefaultCulture;
}
internal void Init(RunspaceContext context)
@ -470,13 +467,26 @@ namespace PSRule.Pipeline
private void Parameter(string[] include, Hashtable tag, string[] convention)
{
_OptionContext.Add(new OptionContext.BaselineScope(type: OptionContext.ScopeType.Parameter, include: include, tag: tag, convention: convention));
_OptionContext.Add(new OptionContext.BaselineScope(
type: OptionContext.ScopeType.Parameter,
include: include,
tag: tag,
convention: convention));
}
private void Workspace(PSRuleOption option)
{
_OptionContext.Add(new OptionContext.BaselineScope(type: OptionContext.ScopeType.Workspace, baselineId: null, moduleName: null, option: option, obsolete: false));
_OptionContext.Add(new OptionContext.ConfigScope(type: OptionContext.ScopeType.Workspace, moduleName: null, option: option));
_OptionContext.Add(new OptionContext.BaselineScope(
type: OptionContext.ScopeType.Workspace,
baselineId: null,
moduleName: null,
option: option,
obsolete: false));
_OptionContext.Add(new OptionContext.ConfigScope(
type: OptionContext.ScopeType.Workspace,
moduleName: null,
option: option));
}
}
}

Просмотреть файл

@ -82,10 +82,7 @@ namespace PSRule.Pipeline.Output
private static bool GetPreferenceVariable(EngineIntrinsics executionContext, string variableName)
{
var preference = GetPreferenceVariable(executionContext.SessionState, variableName);
if (preference == ActionPreference.Ignore)
return false;
return !(preference == ActionPreference.SilentlyContinue && (
return preference != ActionPreference.Ignore && !(preference == ActionPreference.SilentlyContinue && (
variableName == VerbosePreference ||
variableName == DebugPreference)
);

Просмотреть файл

@ -19,12 +19,7 @@ namespace PSRule.Pipeline.Output
protected override string Serialize(object[] o)
{
if (o[0] is IEnumerable<Baseline> baselines)
{
return ToBaselineYaml(baselines);
}
return ToYaml(o);
return o[0] is IEnumerable<Baseline> baselines ? ToBaselineYaml(baselines) : ToYaml(o);
}
internal static string ToYaml(object[] o)

Просмотреть файл

@ -14,7 +14,7 @@ namespace PSRule.Pipeline
{
void Add(string path);
void Add(System.IO.FileInfo[] fileInfo);
void Add(FileInfo[] fileInfo);
void Add(PathInfo[] pathInfo);
@ -86,7 +86,7 @@ namespace PSRule.Pipeline
if (TryUrl(path) || TryPath(path, out path))
return;
var pathLiteral = GetSearchParameters(path, out string searchPattern, out SearchOption searchOption, out PathFilter filter);
var pathLiteral = GetSearchParameters(path, out var searchPattern, out var searchOption, out var filter);
var files = Directory.EnumerateFiles(pathLiteral, searchPattern, searchOption);
foreach (var file in files)
if (ShouldInclude(file, filter))
@ -159,7 +159,7 @@ namespace PSRule.Pipeline
private string GetSearchParameters(string path, out string searchPattern, out SearchOption searchOption, out PathFilter filter)
{
searchOption = SearchOption.AllDirectories;
var pathLiteral = TrimPath(path, out bool relativeAnchor);
var pathLiteral = TrimPath(path, out var relativeAnchor);
if (TryFilter(pathLiteral, out searchPattern, out filter))
return _BasePath;

Просмотреть файл

@ -138,12 +138,12 @@ namespace PSRule.Pipeline
public bool TryMatch(PathStream other, int offset)
{
return other.Peak(offset, out char c) && IsMatch(c);
return other.Peak(offset, out var c) && IsMatch(c);
}
public bool IsUnmatchedSingle(PathStream other, int offset)
{
return other.Peak(offset, out char c) && IsWilcardQ(c) && other.Peak(offset + 1, out char cnext) && IsMatch(cnext);
return other.Peak(offset, out var c) && IsWilcardQ(c) && other.Peak(offset + 1, out var cnext) && IsMatch(cnext);
}
private bool IsMatch(char c)
@ -168,10 +168,7 @@ namespace PSRule.Pipeline
return true;
// Ends in **/
if (pos + 2 == _Path.Length - 1 && IsSeparator(_Path[pos + 2]))
return true;
return false;
return pos + 2 == _Path.Length - 1 && IsSeparator(_Path[pos + 2]);
}
public bool SkipMatchAA()
@ -419,10 +416,12 @@ namespace PSRule.Pipeline
public static PathFilter Create(string basePath, string expression, bool matchResult = true)
{
if (!ShouldSkipExpression(expression))
return new PathFilter(basePath, new PathFilterExpression[] { PathFilterExpression.Create(expression) }, matchResult);
return new PathFilter(basePath, null, matchResult);
return !ShouldSkipExpression(expression)
? new PathFilter(
basePath,
new PathFilterExpression[] { PathFilterExpression.Create(expression) },
matchResult)
: new PathFilter(basePath, null, matchResult);
}
public static PathFilter Create(string basePath, string[] expression, bool matchResult = true)
@ -432,7 +431,9 @@ namespace PSRule.Pipeline
if (!ShouldSkipExpression(expression[i]))
result.Add(PathFilterExpression.Create(expression[i]));
return result.Count == 0 ? new PathFilter(basePath, null, matchResult) : new PathFilter(basePath, result.ToArray(), matchResult);
return result.Count == 0
? new PathFilter(basePath, null, matchResult)
: new PathFilter(basePath, result.ToArray(), matchResult);
}
/// <summary>
@ -454,7 +455,7 @@ namespace PSRule.Pipeline
var cleanPath = start > 0 ? path.Remove(0, start) : path;
// Include unless excluded
bool result = false;
var result = false;
// Compare expressions
for (var i = 0; i < _Expression.Length; i++)
@ -474,10 +475,9 @@ namespace PSRule.Pipeline
private static string NormalDirectoryPath(string path)
{
var c = path[path.Length - 1];
if (c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar)
return path;
return string.Concat(path, Path.DirectorySeparatorChar);
return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar
? path
: string.Concat(path, Path.DirectorySeparatorChar);
}
}
}

Просмотреть файл

@ -203,7 +203,7 @@ namespace PSRule.Pipeline
protected bool RequireModules()
{
var result = true;
if (Option.Requires.TryGetValue(ENGINE_MODULE_NAME, out string requiredVersion))
if (Option.Requires.TryGetValue(ENGINE_MODULE_NAME, out var requiredVersion))
{
var engineVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
if (GuardModuleVersion(ENGINE_MODULE_NAME, engineVersion, requiredVersion))
@ -247,10 +247,9 @@ namespace PSRule.Pipeline
private static bool TryModuleVersion(string moduleVersion, string requiredVersion)
{
if (!(SemanticVersion.TryParseVersion(moduleVersion, out SemanticVersion.Version version) && SemanticVersion.TryParseConstraint(requiredVersion, out SemanticVersion.IConstraint constraint)))
return false;
return constraint.Equals(version);
return SemanticVersion.TryParseVersion(moduleVersion, out var version) &&
SemanticVersion.TryParseConstraint(requiredVersion, out var constraint) &&
constraint.Equals(version);
}
protected PipelineContext PrepareContext(BindTargetMethod bindTargetName, BindTargetMethod bindTargetType, BindTargetMethod bindField)
@ -288,43 +287,30 @@ namespace PSRule.Pipeline
protected virtual PipelineWriter PrepareWriter()
{
var output = GetOutput();
switch (Option.Output.Format)
return Option.Output.Format switch
{
case OutputFormat.Csv:
return new CsvOutputWriter(output, Option);
case OutputFormat.Json:
return new JsonOutputWriter(output, Option);
case OutputFormat.NUnit3:
return new NUnit3OutputWriter(output, Option);
case OutputFormat.Yaml:
return new YamlOutputWriter(output, Option);
case OutputFormat.Markdown:
return new MarkdownOutputWriter(output, Option);
case OutputFormat.Wide:
return new WideOutputWriter(output, Option);
}
return output;
OutputFormat.Csv => new CsvOutputWriter(output, Option),
OutputFormat.Json => new JsonOutputWriter(output, Option),
OutputFormat.NUnit3 => new NUnit3OutputWriter(output, Option),
OutputFormat.Yaml => new YamlOutputWriter(output, Option),
OutputFormat.Markdown => new MarkdownOutputWriter(output, Option),
OutputFormat.Wide => new WideOutputWriter(output, Option),
_ => output,
};
}
protected PipelineWriter GetOutput()
{
// Redirect to file instead
if (!string.IsNullOrEmpty(Option.Output.Path))
{
return new FileOutputWriter(
return !string.IsNullOrEmpty(Option.Output.Path)
? new FileOutputWriter(
inner: _Output,
option: Option,
encoding: GetEncoding(Option.Output.Encoding),
path: Option.Output.Path,
shouldProcess: HostContext.ShouldProcess
);
}
return _Output;
)
: (PipelineWriter)_Output;
}
protected static string[] GetCulture(string[] culture)
@ -352,10 +338,7 @@ namespace PSRule.Pipeline
if (parent.Count > 0)
result.AddRange(parent);
if (result.Count == 0)
return null;
return result.ToArray();
return result.Count == 0 ? null : result.ToArray();
}
/// <summary>
@ -365,26 +348,15 @@ namespace PSRule.Pipeline
/// <returns></returns>
private static Encoding GetEncoding(OutputEncoding? encoding)
{
switch (encoding)
return encoding switch
{
case OutputEncoding.UTF8:
return Encoding.UTF8;
case OutputEncoding.UTF7:
return Encoding.UTF7;
case OutputEncoding.Unicode:
return Encoding.Unicode;
case OutputEncoding.UTF32:
return Encoding.UTF32;
case OutputEncoding.ASCII:
return Encoding.ASCII;
default:
return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
}
OutputEncoding.UTF8 => Encoding.UTF8,
OutputEncoding.UTF7 => Encoding.UTF7,
OutputEncoding.Unicode => Encoding.Unicode,
OutputEncoding.UTF32 => Encoding.UTF32,
OutputEncoding.ASCII => Encoding.ASCII,
_ => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
};
}
private OptionContext GetOptionContext()

Просмотреть файл

@ -164,14 +164,14 @@ namespace PSRule.Pipeline
if (resource.GetApiVersionIssue())
_TrackedIssues.Add(new ResourceIssue(resource.Kind, resource.Id, ResourceIssueType.MissingApiVersion));
if (TryBaseline(resource, out Baseline baseline) && TryBaselineRef(resource.Id, out BaselineRef baselineRef))
if (TryBaseline(resource, out var baseline) && TryBaselineRef(resource.Id, out var baselineRef))
{
_Unresolved.Remove(baselineRef);
Baseline.Add(new OptionContext.BaselineScope(baselineRef.Type, baseline.BaselineId, resource.Module, baseline.Spec, baseline.Obsolete));
}
else if (resource.Kind == ResourceKind.Selector && resource is SelectorV1 selector)
Selector[selector.Id] = new SelectorVisitor(resource.Module, selector.Id, selector.Spec.If);
else if (TryModuleConfig(resource, out ModuleConfigV1 moduleConfig))
else if (TryModuleConfig(resource, out var moduleConfig))
{
if (!string.IsNullOrEmpty(moduleConfig?.Spec?.Rule?.Baseline))
{

Просмотреть файл

@ -21,28 +21,26 @@ namespace PSRule.Pipeline
public static string BindTargetName(string[] propertyNames, bool caseSensitive, bool preferTargetInfo, PSObject targetObject)
{
if (preferTargetInfo && TryGetInfoTargetName(targetObject, out string targetName))
if (preferTargetInfo && TryGetInfoTargetName(targetObject, out var targetName))
return targetName;
if (propertyNames != null)
if (propertyNames.Any(n => n.Contains('.')))
return NestedTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetNameBinding);
else
return CustomTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetNameBinding);
return propertyNames.Any(n => n.Contains('.'))
? NestedTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetNameBinding)
: CustomTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetNameBinding);
return DefaultTargetNameBinding(targetObject);
}
public static string BindTargetType(string[] propertyNames, bool caseSensitive, bool preferTargetInfo, PSObject targetObject)
{
if (preferTargetInfo && TryGetInfoTargetType(targetObject, out string targetType))
if (preferTargetInfo && TryGetInfoTargetType(targetObject, out var targetType))
return targetType;
if (propertyNames != null)
if (propertyNames.Any(n => n.Contains('.')))
return NestedTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetTypeBinding);
else
return CustomTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetTypeBinding);
return propertyNames.Any(n => n.Contains('.'))
? NestedTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetTypeBinding)
: CustomTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultTargetTypeBinding);
return DefaultTargetTypeBinding(targetObject);
}
@ -50,10 +48,9 @@ namespace PSRule.Pipeline
public static string BindField(string[] propertyNames, bool caseSensitive, bool preferTargetInfo, PSObject targetObject)
{
if (propertyNames != null)
if (propertyNames.Any(n => n.Contains('.')))
return NestedTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultFieldBinding);
else
return CustomTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultFieldBinding);
return propertyNames.Any(n => n.Contains('.'))
? NestedTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultFieldBinding)
: CustomTargetPropertyBinding(propertyNames, caseSensitive, targetObject, DefaultFieldBinding);
return DefaultFieldBinding(targetObject);
}
@ -65,12 +62,11 @@ namespace PSRule.Pipeline
/// <returns>The TargetName of the object.</returns>
private static string DefaultTargetNameBinding(PSObject targetObject)
{
if (TryGetInfoTargetName(targetObject, out string targetName) ||
return TryGetInfoTargetName(targetObject, out var targetName) ||
TryGetTargetName(targetObject, propertyName: Property_TargetName, targetName: out targetName) ||
TryGetTargetName(targetObject, propertyName: Property_Name, targetName: out targetName))
return targetName;
return GetUnboundObjectTargetName(targetObject);
TryGetTargetName(targetObject, propertyName: Property_Name, targetName: out targetName)
? targetName
: GetUnboundObjectTargetName(targetObject);
}
/// <summary>
@ -101,10 +97,15 @@ namespace PSRule.Pipeline
private static string NestedTargetPropertyBinding(string[] propertyNames, bool caseSensitive, PSObject targetObject, BindTargetName next)
{
string targetName = null;
int score = int.MaxValue;
var score = int.MaxValue;
for (var i = 0; i < propertyNames.Length && score > propertyNames.Length; i++)
{
if (ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: targetObject, path: propertyNames[i], caseSensitive: caseSensitive, value: out object value))
if (ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: targetObject,
path: propertyNames[i],
caseSensitive: caseSensitive,
value: out object value))
{
targetName = value.ToString();
score = i;
@ -121,7 +122,14 @@ namespace PSRule.Pipeline
/// <returns>The TargetName of the object.</returns>
private static string GetUnboundObjectTargetName(PSObject targetObject)
{
var settings = new JsonSerializerSettings { Formatting = Formatting.None, TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024, Culture = CultureInfo.InvariantCulture };
var settings = new JsonSerializerSettings
{
Formatting = Formatting.None,
TypeNameHandling = TypeNameHandling.None,
MaxDepth = 1024,
Culture = CultureInfo.InvariantCulture
};
settings.Converters.Insert(0, new PSObjectJsonConverter());
var json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(targetObject, settings));
return PipelineContext.CurrentThread.ObjectHashAlgorithm.GetDigest(json);
@ -143,10 +151,7 @@ namespace PSRule.Pipeline
/// <returns>The TargetObject of the object.</returns>
private static string DefaultTargetTypeBinding(PSObject targetObject)
{
if (TryGetInfoTargetType(targetObject, out string targetType))
return targetType;
return targetObject.TypeNames[0];
return TryGetInfoTargetType(targetObject, out var targetType) ? targetType : targetObject.TypeNames[0];
}
private static string DefaultFieldBinding(PSObject targetObject)

Просмотреть файл

@ -194,10 +194,9 @@ namespace PSRule.Pipeline
private static bool GetPreferenceVariable(EngineIntrinsics executionContext, string variableName)
{
var preference = (ActionPreference)executionContext.SessionState.PSVariable.GetValue(variableName);
if (preference == ActionPreference.Ignore)
return false;
return !(preference == ActionPreference.SilentlyContinue && (variableName == VerbosePreference || variableName == DebugPreference));
return preference != ActionPreference.Ignore &&
!(preference == ActionPreference.SilentlyContinue &&
(variableName == VerbosePreference || variableName == DebugPreference));
}
#region Internal logging methods

Просмотреть файл

@ -72,7 +72,7 @@ namespace PSRule.Pipeline
if (!IsAcceptedType(targetObject))
return new TargetObject[] { targetObject };
var reader = ReadAsReader(targetObject, out TargetSourceInfo sourceInfo);
var reader = ReadAsReader(targetObject, out var sourceInfo);
try
{
var d = new JsonSerializer(); // Think about caching this.
@ -101,7 +101,7 @@ namespace PSRule.Pipeline
if (!IsAcceptedType(targetObject))
return new TargetObject[] { targetObject };
var reader = ReadAsReader(targetObject, out TargetSourceInfo sourceInfo);
var reader = ReadAsReader(targetObject, out var sourceInfo);
var d = new DeserializerBuilder()
.IgnoreUnmatchedProperties()
.WithTypeConverter(new PSObjectYamlTypeConverter())
@ -128,10 +128,7 @@ namespace PSRule.Pipeline
result.AddRange(items);
}
if (result.Count == 0)
return EmptyArray;
return result.ToArray();
return result.Count == 0 ? EmptyArray : result.ToArray();
}
catch (Exception ex)
{
@ -154,7 +151,7 @@ namespace PSRule.Pipeline
if (!IsAcceptedType(targetObject))
return new TargetObject[] { targetObject };
var markdown = ReadAsString(targetObject, out TargetSourceInfo sourceInfo);
var markdown = ReadAsString(targetObject, out var sourceInfo);
var value = MarkdownConvert.DeserializeObject(markdown);
return VisitItems(value, sourceInfo, next);
}
@ -165,7 +162,7 @@ namespace PSRule.Pipeline
if (!IsAcceptedType(targetObject))
return new TargetObject[] { targetObject };
var data = ReadAsString(targetObject, out TargetSourceInfo sourceInfo);
var data = ReadAsString(targetObject, out var sourceInfo);
var ast = System.Management.Automation.Language.Parser.ParseInput(data, out _, out _);
var hashtables = ast.FindAll(item => item is System.Management.Automation.Language.HashtableAst, false);
if (hashtables == null)
@ -187,13 +184,18 @@ namespace PSRule.Pipeline
if (!IsGitHead(targetObject))
return new TargetObject[] { targetObject };
var value = PSObject.AsPSObject(GetRepositoryInfo(targetObject, out TargetSourceInfo sourceInfo));
var value = PSObject.AsPSObject(GetRepositoryInfo(targetObject, out var sourceInfo));
return VisitItems(new PSObject[] { value }, sourceInfo, next);
}
public static IEnumerable<TargetObject> ReadObjectPath(TargetObject targetObject, VisitTargetObject source, string objectPath, bool caseSensitive)
{
if (!ObjectHelper.GetPath(bindingContext: null, targetObject: targetObject.Value, path: objectPath, caseSensitive: caseSensitive, value: out object nestedObject))
if (!ObjectHelper.GetPath(
bindingContext: null,
targetObject: targetObject.Value,
path: objectPath,
caseSensitive: caseSensitive,
value: out object nestedObject))
return EmptyArray;
var nestedType = nestedObject.GetType();
@ -227,7 +229,10 @@ namespace PSRule.Pipeline
private static bool IsAcceptedType(TargetObject targetObject)
{
return targetObject.Value.BaseObject is string || targetObject.Value.BaseObject is InputFileInfo || targetObject.Value.BaseObject is FileInfo || targetObject.Value.BaseObject is Uri;
return targetObject.Value.BaseObject is string ||
targetObject.Value.BaseObject is InputFileInfo ||
targetObject.Value.BaseObject is FileInfo ||
targetObject.Value.BaseObject is Uri;
}
private static bool IsGitHead(TargetObject targetObject)
@ -332,7 +337,7 @@ namespace PSRule.Pipeline
if (value == null || source == null)
return;
value.Value.UseTargetInfo(out PSRuleTargetInfo targetInfo);
value.Value.UseTargetInfo(out var targetInfo);
targetInfo.UpdateSource(source);
value.Source.AddRange(targetInfo.Source.ToArray());
value.Issue.AddRange(targetInfo.Issue.ToArray());

Просмотреть файл

@ -117,10 +117,10 @@ namespace PSRule.Pipeline
Name = info.Name;
Version = info.Version?.ToString();
ProjectUri = info.ProjectUri?.ToString();
if (TryPrivateData(info, FIELD_PSRULE, out Hashtable moduleData))
if (TryPrivateData(info, FIELD_PSRULE, out var moduleData))
Baseline = moduleData.ContainsKey(FIELD_BASELINE) ? ResourceHelper.GetIdString(Name, moduleData[FIELD_BASELINE] as string) : null;
if (TryPrivateData(info, FIELD_PSDATA, out Hashtable psData) && psData.ContainsKey(FIELD_PRERELEASE))
if (TryPrivateData(info, FIELD_PSDATA, out var psData) && psData.ContainsKey(FIELD_PRERELEASE))
Version = string.Concat(Version, PRERELEASE_SEPARATOR, psData[FIELD_PRERELEASE].ToString());
}

Просмотреть файл

@ -241,10 +241,7 @@ namespace PSRule.Pipeline
public ITargetBindingContext Using(string languageScope)
{
if (_BindingContext.TryGetValue(languageScope ?? STANDALONE_SCOPE, out ITargetBindingContext result))
return result;
return null;
return _BindingContext.TryGetValue(languageScope ?? STANDALONE_SCOPE, out var result) ? result : null;
}
/// <summary>

Просмотреть файл

@ -57,7 +57,7 @@ namespace PSRule.Pipeline
internal T GetAnnotation<T>() where T : TargetObjectAnnotation, new()
{
if (!_Annotations.TryGetValue(typeof(T), out TargetObjectAnnotation value))
if (!_Annotations.TryGetValue(typeof(T), out var value))
{
value = new T();
_Annotations.Add(typeof(T), value);

Просмотреть файл

@ -49,10 +49,7 @@ namespace PSRule.Rules
private static Runtime.RuleConditionResult GetResult(Collection<Runtime.RuleConditionResult> value)
{
if (value == null || value.Count == 0)
return null;
return value[0];
return value == null || value.Count == 0 ? null : value[0];
}
}
}

Просмотреть файл

@ -48,10 +48,7 @@ namespace PSRule.Rules
internal bool Match(string name, ResourceTags tag)
{
if (IsExcluded(name))
return false;
return IsIncluded(name, tag);
return !IsExcluded(name) && IsIncluded(name, tag);
}
/// <summary>
@ -60,13 +57,9 @@ namespace PSRule.Rules
/// <returns>Return true if rule is matched, otherwise false.</returns>
public bool Match(IResource resource)
{
if (IsExcluded(resource.Name))
return false;
if (_IncludeLocal && resource.IsLocalScope())
return true;
return IsIncluded(resource.Name, resource.Tags);
return !IsExcluded(resource.Name) &&
(_IncludeLocal && resource.IsLocalScope() ||
IsIncluded(resource.Name, resource.Tags));
}
private bool IsExcluded(string name)

Просмотреть файл

@ -102,7 +102,7 @@ namespace PSRule.Rules
if (Annotations == null || !Annotations.ContainsKey(ONLINE_HELP_LINK_ANNOTATION))
return null;
if (Uri.TryCreate(Annotations[ONLINE_HELP_LINK_ANNOTATION].ToString(), UriKind.Absolute, out Uri result))
if (Uri.TryCreate(Annotations[ONLINE_HELP_LINK_ANNOTATION].ToString(), UriKind.Absolute, out var result))
return result;
return null;

Просмотреть файл

@ -71,7 +71,7 @@ namespace PSRule.Rules
unchecked
{
// Get combined hash code for key
uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
var rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
return ((int)rol5 + h1) ^ h2;
}
}
@ -79,10 +79,10 @@ namespace PSRule.Rules
public bool Match(string ruleName, string targetName)
{
if (_IsEmpty || string.IsNullOrEmpty(ruleName) || string.IsNullOrEmpty(targetName))
return false;
return _Index.Contains(new SuppressionKey(ruleName, targetName));
return !_IsEmpty &&
!string.IsNullOrEmpty(ruleName) &&
!string.IsNullOrEmpty(targetName) &&
_Index.Contains(new SuppressionKey(ruleName, targetName));
}
private void Index(SuppressionOption option)

Просмотреть файл

@ -127,12 +127,12 @@ namespace PSRule.Runtime
public AssertResult JsonSchema(PSObject inputObject, string uri)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(uri, nameof(uri), out result))
return result;
// Get the schema
if (!(TryReadJson(uri, out string schemaContent)))
if (!TryReadJson(uri, out var schemaContent))
return Fail(ReasonStrings.JsonSchemaNotFound, uri);
var s = new JsonSerializer();
@ -178,18 +178,17 @@ namespace PSRule.Runtime
public AssertResult HasJsonSchema(PSObject inputObject, string[] uri = null, bool ignoreScheme = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
GuardField(inputObject, PROPERTY_SCHEMA, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string actualSchema, out result))
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardField(inputObject, PROPERTY_SCHEMA, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var actualSchema, out result))
return result;
if (string.IsNullOrEmpty(actualSchema))
return Fail(ReasonStrings.NotHasFieldValue, PROPERTY_SCHEMA);
if (uri == null || uri.Length == 0 || ExpressionHelpers.AnySchema(actualSchema, uri, ignoreScheme, false))
return Pass();
return Fail(ReasonStrings.Assert_NotSpecifiedSchema, actualSchema);
return uri == null || uri.Length == 0 || ExpressionHelpers.AnySchema(actualSchema, uri, ignoreScheme, false)
? Pass()
: Fail(ReasonStrings.Assert_NotSpecifiedSchema, actualSchema);
}
/// <summary>
@ -198,7 +197,7 @@ namespace PSRule.Runtime
public AssertResult HasField(PSObject inputObject, string[] field, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
@ -219,14 +218,19 @@ namespace PSRule.Runtime
public AssertResult NotHasField(PSObject inputObject, string[] field, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
result = Pass();
for (var i = 0; field != null && i < field.Length; i++)
{
if (ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field[i], caseSensitive: caseSensitive, value: out object _))
if (ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field[i],
caseSensitive: caseSensitive,
value: out object _))
{
if (result.Result)
result = Fail();
@ -243,7 +247,7 @@ namespace PSRule.Runtime
public AssertResult HasFields(PSObject inputObject, string[] field, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
@ -251,7 +255,12 @@ namespace PSRule.Runtime
var missing = 0;
for (var i = 0; field != null && i < field.Length; i++)
{
if (!ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field[i], caseSensitive: caseSensitive, value: out object _))
if (!ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field[i],
caseSensitive: caseSensitive,
value: out object _))
{
result.AddReason(ReasonStrings.NotHasField, field[i]);
missing++;
@ -266,12 +275,17 @@ namespace PSRule.Runtime
public AssertResult HasFieldValue(PSObject inputObject, string field, object expectedValue = null)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
// Assert
if (!ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field, caseSensitive: false, value: out object fieldValue))
if (!ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field,
caseSensitive: false,
value: out object fieldValue))
return Fail(ReasonStrings.NotHasField, field);
else if (ExpressionHelpers.NullOrEmpty(fieldValue))
return Fail(ReasonStrings.NotHasFieldValue, field);
@ -287,16 +301,20 @@ namespace PSRule.Runtime
public AssertResult HasDefaultValue(PSObject inputObject, string field, object defaultValue)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
// Assert
if (!ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field, caseSensitive: false, value: out object fieldValue)
|| ExpressionHelpers.Equal(defaultValue, fieldValue, caseSensitive: false))
return Pass();
return Fail(ReasonStrings.HasExpectedFieldValue, field, fieldValue);
return !ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field,
caseSensitive: false,
value: out object fieldValue)
|| ExpressionHelpers.Equal(defaultValue, fieldValue, caseSensitive: false)
? Pass()
: Fail(ReasonStrings.HasExpectedFieldValue, field, fieldValue);
}
/// <summary>
@ -305,11 +323,16 @@ namespace PSRule.Runtime
public AssertResult Null(PSObject inputObject, string field)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field, caseSensitive: false, value: out object fieldValue);
ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field,
caseSensitive: false,
value: out object fieldValue);
return fieldValue == null ? Pass() : Fail(ReasonStrings.NotNull, field);
}
@ -319,9 +342,9 @@ namespace PSRule.Runtime
public AssertResult NotNull(PSObject inputObject, string field)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
return fieldValue == null ? Fail(ReasonStrings.Null, field) : Pass();
@ -333,15 +356,19 @@ namespace PSRule.Runtime
public AssertResult NullOrEmpty(PSObject inputObject, string field)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
// Assert
if (ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field, caseSensitive: false, value: out object fieldValue) && !ExpressionHelpers.NullOrEmpty(fieldValue))
return Fail(ReasonStrings.NullOrEmpty, field);
return Pass();
return ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field,
caseSensitive: false,
value: out object fieldValue) && !ExpressionHelpers.NullOrEmpty(fieldValue)
? Fail(ReasonStrings.NullOrEmpty, field)
: Pass();
}
/// <summary>
@ -350,11 +377,11 @@ namespace PSRule.Runtime
public AssertResult StartsWith(PSObject inputObject, string field, string[] prefix, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullParam(prefix, nameof(prefix), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
if (prefix == null || prefix.Length == 0)
@ -375,11 +402,11 @@ namespace PSRule.Runtime
public AssertResult EndsWith(PSObject inputObject, string field, string[] suffix, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullParam(suffix, nameof(suffix), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
if (suffix == null || suffix.Length == 0)
@ -400,11 +427,11 @@ namespace PSRule.Runtime
public AssertResult Contains(PSObject inputObject, string field, string[] text, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullParam(text, nameof(text), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
if (text == null || text.Length == 0)
@ -425,13 +452,13 @@ namespace PSRule.Runtime
public AssertResult IsLower(PSObject inputObject, string field, bool requireLetters = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
if (!ExpressionHelpers.IsLower(value, requireLetters, out bool notLetters))
if (!ExpressionHelpers.IsLower(value, requireLetters, out var notLetters))
return Fail(notLetters ? ReasonStrings.IsLetter : ReasonStrings.Assert_IsLower, value);
return Pass();
@ -443,13 +470,13 @@ namespace PSRule.Runtime
public AssertResult IsUpper(PSObject inputObject, string field, bool requireLetters = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
if (!ExpressionHelpers.IsUpper(value, requireLetters, out bool notLetters))
if (!ExpressionHelpers.IsUpper(value, requireLetters, out var notLetters))
return Fail(notLetters ? ReasonStrings.IsLetter : ReasonStrings.Assert_IsUpper, value);
return Pass();
@ -461,17 +488,19 @@ namespace PSRule.Runtime
public AssertResult IsNumeric(PSObject inputObject, string field, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
if (ExpressionHelpers.TryInt(fieldValue, convert, out _) || ExpressionHelpers.TryLong(fieldValue, convert, out _) || ExpressionHelpers.TryFloat(fieldValue, convert, out _) ||
ExpressionHelpers.TryByte(fieldValue, convert, out _) || ExpressionHelpers.TryDouble(fieldValue, convert, out _))
return Pass();
return Fail(ReasonStrings.TypeNumeric, GetTypeName(fieldValue), fieldValue);
return ExpressionHelpers.TryInt(fieldValue, convert, out _) ||
ExpressionHelpers.TryLong(fieldValue, convert, out _) ||
ExpressionHelpers.TryFloat(fieldValue, convert, out _) ||
ExpressionHelpers.TryByte(fieldValue, convert, out _) ||
ExpressionHelpers.TryDouble(fieldValue, convert, out _)
? Pass()
: Fail(ReasonStrings.TypeNumeric, GetTypeName(fieldValue), fieldValue);
}
/// <summary>
@ -480,16 +509,17 @@ namespace PSRule.Runtime
public AssertResult IsInteger(PSObject inputObject, string field, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
if (ExpressionHelpers.TryInt(fieldValue, convert, out _) || ExpressionHelpers.TryLong(fieldValue, convert, out _) || ExpressionHelpers.TryByte(fieldValue, convert, out _))
return Pass();
return Fail(ReasonStrings.TypeInteger, GetTypeName(fieldValue), fieldValue);
return ExpressionHelpers.TryInt(fieldValue, convert, out _) ||
ExpressionHelpers.TryLong(fieldValue, convert, out _) ||
ExpressionHelpers.TryByte(fieldValue, convert, out _)
? Pass()
: Fail(ReasonStrings.TypeInteger, GetTypeName(fieldValue), fieldValue);
}
/// <summary>
@ -498,16 +528,15 @@ namespace PSRule.Runtime
public AssertResult IsBoolean(PSObject inputObject, string field, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
if (ExpressionHelpers.TryBool(fieldValue, convert, out _))
return Pass();
return Fail(ReasonStrings.Type, TYPENAME_BOOL, GetTypeName(fieldValue), fieldValue);
return ExpressionHelpers.TryBool(fieldValue, convert, out _)
? Pass()
: Fail(ReasonStrings.Type, TYPENAME_BOOL, GetTypeName(fieldValue), fieldValue);
}
/// <summary>
@ -516,17 +545,14 @@ namespace PSRule.Runtime
public AssertResult IsArray(PSObject inputObject, string field)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
var o = GetBaseObject(fieldValue);
if (o is Array)
return Pass();
return Fail(ReasonStrings.Type, TYPENAME_ARRAY, GetTypeName(fieldValue), fieldValue);
return o is Array ? Pass() : Fail(ReasonStrings.Type, TYPENAME_ARRAY, GetTypeName(fieldValue), fieldValue);
}
/// <summary>
@ -535,16 +561,15 @@ namespace PSRule.Runtime
public AssertResult IsString(PSObject inputObject, string field)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
if (ExpressionHelpers.TryString(fieldValue, out _))
return Pass();
return Fail(ReasonStrings.Type, TYPENAME_STRING, GetTypeName(fieldValue), fieldValue);
return ExpressionHelpers.TryString(fieldValue, out _)
? Pass()
: Fail(ReasonStrings.Type, TYPENAME_STRING, GetTypeName(fieldValue), fieldValue);
}
/// <summary>
@ -553,16 +578,15 @@ namespace PSRule.Runtime
public AssertResult IsDateTime(PSObject inputObject, string field, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
if (ExpressionHelpers.TryDateTime(fieldValue, convert, out _))
return Pass();
return Fail(ReasonStrings.Type, TYPENAME_DATETIME, GetTypeName(fieldValue), fieldValue);
return ExpressionHelpers.TryDateTime(fieldValue, convert, out _)
? Pass()
: Fail(ReasonStrings.Type, TYPENAME_DATETIME, GetTypeName(fieldValue), fieldValue);
}
/// <summary>
@ -571,10 +595,10 @@ namespace PSRule.Runtime
public AssertResult TypeOf(PSObject inputObject, string field, Type[] type)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullOrEmptyParam(type, nameof(type), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
@ -582,7 +606,9 @@ namespace PSRule.Runtime
for (var i = 0; type != null && i < type.Length; i++)
{
var o = GetBaseObject(fieldValue);
if (type[i].IsAssignableFrom(fieldValue.GetType()) || type[i].IsAssignableFrom(o.GetType()) || TryTypeName(fieldValue, type[i].FullName))
if (type[i].IsAssignableFrom(fieldValue.GetType()) ||
type[i].IsAssignableFrom(o.GetType()) ||
TryTypeName(fieldValue, type[i].FullName))
return Pass();
result.AddReason(ReasonStrings.Type, type[i].Name, GetTypeName(fieldValue), fieldValue);
@ -596,10 +622,10 @@ namespace PSRule.Runtime
public AssertResult TypeOf(PSObject inputObject, string field, string[] type)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullOrEmptyParam(type, nameof(type), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardNullFieldValue(field, fieldValue, out result))
return result;
@ -607,7 +633,9 @@ namespace PSRule.Runtime
for (var i = 0; type != null && i < type.Length; i++)
{
var o = GetBaseObject(fieldValue);
if (StringComparer.OrdinalIgnoreCase.Equals(fieldValue.GetType().FullName, type[i]) || StringComparer.OrdinalIgnoreCase.Equals(o.GetType().FullName, type[i]) || TryTypeName(fieldValue, type[i]))
if (StringComparer.OrdinalIgnoreCase.Equals(fieldValue.GetType().FullName, type[i]) ||
StringComparer.OrdinalIgnoreCase.Equals(o.GetType().FullName, type[i]) ||
TryTypeName(fieldValue, type[i]))
return Pass();
result.AddReason(ReasonStrings.Type, type[i], GetTypeName(fieldValue), fieldValue);
@ -621,31 +649,28 @@ namespace PSRule.Runtime
public AssertResult Version(PSObject inputObject, string field, string constraint = null, bool includePrerelease = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardSemanticVersion(fieldValue, out SemanticVersion.Version value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardSemanticVersion(fieldValue, out var value, out result))
return result;
if (!SemanticVersion.TryParseConstraint(constraint, out SemanticVersion.IConstraint c, includePrerelease))
if (!SemanticVersion.TryParseConstraint(constraint, out var c, includePrerelease))
throw new RuleException(string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.VersionConstraintInvalid, value));
// Assert
if (c != null && !c.Equals(value))
return Fail(ReasonStrings.VersionContraint, value, constraint);
return Pass();
return c != null && !c.Equals(value) ? Fail(ReasonStrings.VersionContraint, value, constraint) : Pass();
}
public AssertResult Greater(PSObject inputObject, string field, int value, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out int compare, out object actual))
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out var compare, out var actual))
return compare > 0 ? Pass() : Fail(ReasonStrings.Greater, actual, value);
return Fail(ReasonStrings.Compare, fieldValue, value);
@ -654,12 +679,12 @@ namespace PSRule.Runtime
public AssertResult GreaterOrEqual(PSObject inputObject, string field, int value, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out int compare, out object actual))
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out var compare, out var actual))
return compare >= 0 ? Pass() : Fail(ReasonStrings.GreaterOrEqual, actual, value);
return Fail(ReasonStrings.Compare, fieldValue, value);
@ -668,12 +693,12 @@ namespace PSRule.Runtime
public AssertResult Less(PSObject inputObject, string field, int value, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out int compare, out object actual))
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out var compare, out var actual))
return compare < 0 ? Pass() : Fail(ReasonStrings.Less, actual, value);
return Fail(ReasonStrings.Compare, fieldValue, value);
@ -682,12 +707,12 @@ namespace PSRule.Runtime
public AssertResult LessOrEqual(PSObject inputObject, string field, int value, bool convert = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out int compare, out object actual))
if (ExpressionHelpers.CompareNumeric(fieldValue, value, convert, out var compare, out var actual))
return compare <= 0 ? Pass() : Fail(ReasonStrings.LessOrEqual, actual, value);
return Fail(ReasonStrings.Compare, fieldValue, value);
@ -699,15 +724,15 @@ namespace PSRule.Runtime
public AssertResult In(PSObject inputObject, string field, Array values, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullParam(values, nameof(values), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
for (var i = 0; values != null && i < values.Length; i++)
{
if (ExpressionHelpers.AnyValue(fieldValue, values.GetValue(i), caseSensitive, out object _))
if (ExpressionHelpers.AnyValue(fieldValue, values.GetValue(i), caseSensitive, out var _))
return Pass();
}
return Fail(ReasonStrings.In, fieldValue);
@ -719,17 +744,22 @@ namespace PSRule.Runtime
public AssertResult NotIn(PSObject inputObject, string field, Array values, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullParam(values, nameof(values), out result))
return result;
if (!ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field, caseSensitive: caseSensitive, value: out object fieldValue))
if (!ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field,
caseSensitive: caseSensitive,
value: out object fieldValue))
return Pass();
for (var i = 0; values != null && i < values.Length; i++)
{
if (ExpressionHelpers.AnyValue(fieldValue, values.GetValue(i), caseSensitive, out object foundValue))
if (ExpressionHelpers.AnyValue(fieldValue, values.GetValue(i), caseSensitive, out var foundValue))
return Fail(ReasonStrings.NotIn, foundValue);
}
return Pass();
@ -741,16 +771,16 @@ namespace PSRule.Runtime
public AssertResult Subset(PSObject inputObject, string field, Array values, bool caseSensitive = false, bool unique = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullParam(values, nameof(values), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardFieldEnumerable(fieldValue, field, out _, out result))
return result;
for (var i = 0; values != null && i < values.Length; i++)
{
if (!ExpressionHelpers.CountValue(fieldValue, values.GetValue(i), caseSensitive, out int count) || (count > 1 && unique))
if (!ExpressionHelpers.CountValue(fieldValue, values.GetValue(i), caseSensitive, out var count) || (count > 1 && unique))
return count == 0 ? Fail(ReasonStrings.Subset, field, values.GetValue(i)) : Fail(ReasonStrings.SubsetDuplicate, field, values.GetValue(i));
}
return Pass();
@ -759,11 +789,11 @@ namespace PSRule.Runtime
public AssertResult SetOf(PSObject inputObject, string field, Array values, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullParam(values, nameof(values), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardFieldEnumerable(fieldValue, field, out int count, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardFieldEnumerable(fieldValue, field, out var count, out result))
return result;
if (count != values.Length)
@ -783,10 +813,10 @@ namespace PSRule.Runtime
public AssertResult Count(PSObject inputObject, string field, int count)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardFieldEnumerable(fieldValue, field, out int actual, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardFieldEnumerable(fieldValue, field, out var actual, out result))
return result;
return actual == count ? Pass() : Fail(ReasonStrings.Count, field, actual, count);
@ -798,16 +828,13 @@ namespace PSRule.Runtime
public AssertResult Match(PSObject inputObject, string field, string pattern, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
if (ExpressionHelpers.Match(pattern, value, caseSensitive))
return Pass();
return Fail(ReasonStrings.MatchPattern, value, pattern);
return ExpressionHelpers.Match(pattern, value, caseSensitive) ? Pass() : Fail(ReasonStrings.MatchPattern, value, pattern);
}
/// <summary>
@ -816,14 +843,19 @@ namespace PSRule.Runtime
public AssertResult NotMatch(PSObject inputObject, string field, string pattern, bool caseSensitive = false)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result))
return result;
if (!ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field, caseSensitive: caseSensitive, value: out object fieldValue))
if (!ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field,
caseSensitive: caseSensitive,
value: out object fieldValue))
return Pass();
if (GuardString(fieldValue, out string value, out result))
if (GuardString(fieldValue, out var value, out result))
return result;
if (!ExpressionHelpers.Match(pattern, value, caseSensitive))
@ -835,18 +867,15 @@ namespace PSRule.Runtime
public AssertResult FilePath(PSObject inputObject, string field, string[] suffix = null)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
if (suffix == null || suffix.Length == 0)
{
if (!TryFilePath(value, out _))
return Fail(ReasonStrings.FilePath, value);
return Pass();
return !TryFilePath(value, out _) ? Fail(ReasonStrings.FilePath, value) : Pass();
}
var reason = Fail();
@ -863,10 +892,10 @@ namespace PSRule.Runtime
public AssertResult FileHeader(PSObject inputObject, string field, string[] header, string prefix = null)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result) ||
GuardString(fieldValue, out string value, out result))
GuardField(inputObject, field, false, out var fieldValue, out result) ||
GuardString(fieldValue, out var value, out result))
return result;
// File does not exist
@ -893,10 +922,7 @@ namespace PSRule.Runtime
}
// Catch file has less lines than header
if (lineNo < header.Length)
return Fail(ReasonStrings.FileHeader);
return Pass();
return lineNo < header.Length ? Fail(ReasonStrings.FileHeader) : Pass();
}
/// <summary>
@ -905,10 +931,10 @@ namespace PSRule.Runtime
public AssertResult WithinPath(PSObject inputObject, string field, string[] path, bool? caseSensitive = null)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullOrEmptyParam(path, nameof(path), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
var fieldValuePath = ExpressionHelpers.GetObjectOriginPath(fieldValue);
@ -932,10 +958,10 @@ namespace PSRule.Runtime
public AssertResult NotWithinPath(PSObject inputObject, string field, string[] path, bool? caseSensitive = null)
{
// Guard parameters
if (GuardNullParam(inputObject, nameof(inputObject), out AssertResult result) ||
if (GuardNullParam(inputObject, nameof(inputObject), out var result) ||
GuardNullOrEmptyParam(field, nameof(field), out result) ||
GuardNullOrEmptyParam(path, nameof(path), out result) ||
GuardField(inputObject, field, false, out object fieldValue, out result))
GuardField(inputObject, field, false, out var fieldValue, out result))
return result;
var fieldValuePath = ExpressionHelpers.GetObjectOriginPath(fieldValue);
@ -1008,7 +1034,12 @@ namespace PSRule.Runtime
private bool GuardField(PSObject inputObject, string field, bool caseSensitive, out object fieldValue, out AssertResult result)
{
result = null;
if (ObjectHelper.GetPath(bindingContext: PipelineContext.CurrentThread, targetObject: inputObject, path: field, caseSensitive: caseSensitive, value: out fieldValue))
if (ObjectHelper.GetPath(
bindingContext: PipelineContext.CurrentThread,
targetObject: inputObject,
path: field,
caseSensitive: caseSensitive,
value: out fieldValue))
return false;
result = Fail(ReasonStrings.NotHasField, field);
@ -1019,7 +1050,7 @@ namespace PSRule.Runtime
{
result = null;
value = null;
if (ExpressionHelpers.TryString(fieldValue, out string sversion) && Runtime.SemanticVersion.TryParseVersion(sversion, out value))
if (ExpressionHelpers.TryString(fieldValue, out var sversion) && Runtime.SemanticVersion.TryParseVersion(sversion, out value))
return false;
result = Fail(ReasonStrings.Version, fieldValue);
@ -1090,7 +1121,7 @@ namespace PSRule.Runtime
json = webClient.DownloadString(uri);
return true;
}
else if (TryFilePath(uri, out string path))
else if (TryFilePath(uri, out var path))
{
using var reader = new StreamReader(path);
json = reader.ReadToEnd();

Просмотреть файл

@ -112,10 +112,7 @@ namespace PSRule.Runtime
/// <returns></returns>
public AssertResult ReasonIf(bool condition, string text, params object[] args)
{
if (!condition)
return this;
return Reason(text, args);
return !condition ? this : Reason(text, args);
}
/// <summary>

Просмотреть файл

@ -31,7 +31,7 @@ namespace PSRule.Runtime
public string[] GetStringValues(string configurationKey)
{
if (!TryGetValue(configurationKey, out object value) || value == null)
if (!TryGetValue(configurationKey, out var value) || value == null)
return System.Array.Empty<string>();
if (value is string valueT)
@ -53,26 +53,17 @@ namespace PSRule.Runtime
public object GetValueOrDefault(string configurationKey, object defaultValue)
{
if (!TryGetValue(configurationKey, out object value) || value == null)
return defaultValue;
return value;
return !TryGetValue(configurationKey, out var value) || value == null ? defaultValue : value;
}
public bool GetBoolOrDefault(string configurationKey, bool defaultValue)
{
if (!TryGetValue(configurationKey, out object value) || !TryBool(value, out bool result))
return defaultValue;
return result;
return !TryGetValue(configurationKey, out var value) || !TryBool(value, out var result) ? defaultValue : result;
}
public int GetIntegerOrDefault(string configurationKey, int defaultValue)
{
if (!TryGetValue(configurationKey, out object value) || !TryInt(value, out int result))
return defaultValue;
return result;
return !TryGetValue(configurationKey, out var value) || !TryInt(value, out var result) ? defaultValue : result;
}
private bool TryGetValue(string name, out object value)
@ -82,7 +73,7 @@ namespace PSRule.Runtime
return false;
// Get from baseline configuration
if (_Context.LanguageScope.TryConfigurationValue(name, out object result))
if (_Context.LanguageScope.TryConfigurationValue(name, out var result))
{
value = result;
return true;

Просмотреть файл

@ -61,10 +61,7 @@ namespace PSRule.Runtime
public bool TryConfigurationValue(string key, out object value)
{
value = null;
if (string.IsNullOrEmpty(key))
return false;
return _Configuration.TryGetValue(key, out value);
return !string.IsNullOrEmpty(key) && _Configuration.TryGetValue(key, out value);
}
public void WithFilter(IResourceFilter resourceFilter)
@ -74,7 +71,7 @@ namespace PSRule.Runtime
public IResourceFilter GetFilter(ResourceKind kind)
{
return _Filter.TryGetValue(kind, out IResourceFilter filter) ? filter : null;
return _Filter.TryGetValue(kind, out var filter) ? filter : null;
}
public void AddService(string name, object service)
@ -87,7 +84,7 @@ namespace PSRule.Runtime
public object GetService(string name)
{
return _Service.TryGetValue(name, out object service) ? service : null;
return _Service.TryGetValue(name, out var service) ? service : null;
}
private void Dispose(bool disposing)
@ -152,7 +149,7 @@ namespace PSRule.Runtime
internal void UseScope(string name)
{
if (_Scopes.TryGetValue(GetScopeName(name), out ILanguageScope scope))
if (_Scopes.TryGetValue(GetScopeName(name), out var scope))
_Current = scope;
}

Просмотреть файл

@ -34,7 +34,7 @@ namespace PSRule.Runtime
if (RunspaceContext.CurrentThread.Pipeline.LocalizedDataCache.ContainsKey(path))
return RunspaceContext.CurrentThread.Pipeline.LocalizedDataCache[path];
var ast = System.Management.Automation.Language.Parser.ParseFile(path, out Token[] tokens, out ParseError[] errors);
var ast = System.Management.Automation.Language.Parser.ParseFile(path, out var tokens, out var errors);
var data = ast.Find(a => a is HashtableAst, false);
if (data != null)
{

Просмотреть файл

@ -69,7 +69,7 @@ namespace PSRule.Runtime
private static PathExpression GetPathExpression(IBindingContext bindingContext, string path)
{
// Try to load nameToken from cache
if (bindingContext == null || !bindingContext.GetPathExpression(path, out PathExpression expression))
if (bindingContext == null || !bindingContext.GetPathExpression(path, out var expression))
{
expression = PathExpression.Create(path);
if (bindingContext != null)

Просмотреть файл

@ -50,7 +50,7 @@ namespace PSRule.Runtime.ObjectPath
private PathExpressionFn BuildSelector(ITokenReader reader)
{
if (!reader.Peak(out IPathToken token) || token.Type == PathTokenType.EndFilter || token.Type == PathTokenType.EndGroup)
if (!reader.Peak(out var token) || token.Type == PathTokenType.EndFilter || token.Type == PathTokenType.EndGroup)
return Return;
reader.Next(out token);
@ -101,7 +101,7 @@ namespace PSRule.Runtime.ObjectPath
if (!filter(context, i))
continue;
if (!next(context, i, out IEnumerable<object> items))
if (!next(context, i, out var items))
continue;
success++;
@ -118,10 +118,7 @@ namespace PSRule.Runtime.ObjectPath
return (IPathExpressionContext context, object input, out IEnumerable<object> value) =>
{
value = null;
if (!TryGetIndex(input, index, out object item))
return false;
return next(context, item, out value);
return TryGetIndex(input, index, out var item) && next(context, item, out value);
};
}
@ -135,7 +132,7 @@ namespace PSRule.Runtime.ObjectPath
var success = 0;
foreach (var i in GetAll(input))
{
if (!next(context, i, out IEnumerable<object> items))
if (!next(context, i, out var items))
continue;
success++;
@ -157,10 +154,10 @@ namespace PSRule.Runtime.ObjectPath
{
var result = new List<object>();
var currentIndex = start;
while ((!end.HasValue || (step > 0 && currentIndex < end) || (step < 0 && currentIndex > end)) && TryGetIndex(input, currentIndex, out object slice))
while ((!end.HasValue || (step > 0 && currentIndex < end) || (step < 0 && currentIndex > end)) && TryGetIndex(input, currentIndex, out var slice))
{
currentIndex += step;
if (!next(context, slice, out IEnumerable<object> items))
if (!next(context, slice, out var items))
continue;
result.AddRange(items);
@ -178,10 +175,7 @@ namespace PSRule.Runtime.ObjectPath
{
value = null;
var caseSensitive = context.CaseSensitive != caseSensitiveFlag;
if (!TryGetField(input, memberName, caseSensitive, out object item))
return false;
return next(context, item, out value);
return TryGetField(input, memberName, caseSensitive, out var item) && next(context, item, out value);
};
}
@ -200,7 +194,7 @@ namespace PSRule.Runtime.ObjectPath
private PathExpressionFilterFn BuildExpression(ITokenReader reader, PathTokenType stop)
{
var result = new Stack<PathExpressionFilterFn>(4);
while (reader.Next(out IPathToken token) && token.Type != stop)
while (reader.Next(out var token) && token.Type != stop)
{
if (token.Type == PathTokenType.LogicalOperator && token.As<FilterOperator>() == FilterOperator.Or)
continue;
@ -275,7 +269,7 @@ namespace PSRule.Runtime.ObjectPath
{
return (IPathExpressionContext context, object input) =>
{
if (!left(context, input, out IEnumerable<object> leftValue) || !right(context, input, out IEnumerable<object> rightValue))
if (!left(context, input, out var leftValue) || !right(context, input, out var rightValue))
return false;
var operand1 = leftValue.FirstOrDefault();
@ -291,7 +285,7 @@ namespace PSRule.Runtime.ObjectPath
return !ExpressionHelpers.Equal(operand1, operand2, context.CaseSensitive);
case FilterOperator.Less:
return ExpressionHelpers.CompareNumeric(operand1, operand2, convert: false, compare: out int compare, value: out _) && compare < 0;
return ExpressionHelpers.CompareNumeric(operand1, operand2, convert: false, compare: out var compare, value: out _) && compare < 0;
case FilterOperator.LessOrEqual:
return ExpressionHelpers.CompareNumeric(operand1, operand2, convert: false, compare: out compare, value: out _) && compare <= 0;
@ -334,10 +328,7 @@ namespace PSRule.Runtime.ObjectPath
private static IEnumerable<object> GetAll(object o)
{
var baseObject = GetBaseObject(o);
if (baseObject is IEnumerable)
return GetAllIndex(baseObject);
return GetAllField(baseObject);
return baseObject is IEnumerable ? GetAllIndex(baseObject) : GetAllField(baseObject);
}
private static IEnumerable<object> GetAllIndex(object o)
@ -537,7 +528,7 @@ namespace PSRule.Runtime.ObjectPath
private static bool TryPropertyValue(JObject targetObject, string propertyName, bool caseSensitive, out object value)
{
value = null;
if (!targetObject.TryGetValue(propertyName, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase, out JToken result))
if (!targetObject.TryGetValue(propertyName, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase, out var result))
return false;
value = GetTokenValue(result);

Просмотреть файл

@ -194,7 +194,7 @@ namespace PSRule.Runtime.ObjectPath
if (!IsQuoted(Current(position)))
return false;
if (!UntilQuote(ref position, out string value))
if (!UntilQuote(ref position, out var value))
return false;
tokens.Add(new PathToken(PathTokenType.String, value));
@ -205,7 +205,7 @@ namespace PSRule.Runtime.ObjectPath
private bool TryConsumeNumberLiteral(ref int position, ITokenWriter tokens)
{
var pos = SkipPadding(position);
if (!TryInteger(pos, out int value))
if (!TryInteger(pos, out var value))
return false;
tokens.Add(new PathToken(PathTokenType.Integer, value));
@ -216,7 +216,7 @@ namespace PSRule.Runtime.ObjectPath
private bool TryConsumeBooleanLiteral(ref int position, ITokenWriter tokens)
{
var pos = SkipPadding(position);
if (!TryBoolean(pos, out bool value))
if (!TryBoolean(pos, out var value))
return false;
tokens.Add(new PathToken(PathTokenType.Boolean, value));
@ -398,7 +398,7 @@ namespace PSRule.Runtime.ObjectPath
var slice = new int?[] { null, null, null };
for (var i = 0; i <= 2 && pos <= Last && Path[pos] != INDEX_CLOSE; i++)
{
if (WhileNumeric(pos, out int end) && end > pos)
if (WhileNumeric(pos, out var end) && end > pos)
{
slice[i] = int.Parse(Substring(pos, end));
pos = Current(end, COLON) ? end + 1 : end;
@ -418,24 +418,21 @@ namespace PSRule.Runtime.ObjectPath
/// </summary>
private bool TryConsumeUnionSelector(ref int position, ITokenWriter tokens)
{
if (!AnyUntilIndexClose(position, COMMA))
return false;
return TryConsumeUnionQuotedMemberSelector(ref position, tokens) ||
TryConsumeUnionIndexSelector(ref position, tokens);
return AnyUntilIndexClose(position, COMMA) &&
(TryConsumeUnionQuotedMemberSelector(ref position, tokens) || TryConsumeUnionIndexSelector(ref position, tokens));
}
private bool TryConsumeUnionIndexSelector(ref int position, ITokenWriter tokens)
{
var pos = SkipPadding(position);
if (pos + 2 >= Last || !WhileNumeric(pos, out int end) || end == pos)
if (pos + 2 >= Last || !WhileNumeric(pos, out var end) || end == pos)
return false;
var members = new List<int>();
while (pos <= Last && Path[pos] != INDEX_CLOSE)
{
pos = SkipPadding(pos);
if (!WhileNumeric(pos, out end) || !int.TryParse(Substring(pos, end), out int member))
if (!WhileNumeric(pos, out end) || !int.TryParse(Substring(pos, end), out var member))
break;
members.Add(member);
@ -515,7 +512,7 @@ namespace PSRule.Runtime.ObjectPath
private bool TryConsumeNumericIndex(ref int position, ITokenWriter tokens)
{
var pos = SkipPadding(position);
if (!WhileNumeric(pos, out int end) || !int.TryParse(Substring(pos, end), out int index))
if (!WhileNumeric(pos, out var end) || !int.TryParse(Substring(pos, end), out var index))
return false;
pos = SkipPadding(end);
@ -529,7 +526,7 @@ namespace PSRule.Runtime.ObjectPath
private string CaptureMemberName(ref int position)
{
return UntilQuote(ref position, out string value) || WhileMemberName(ref position, out value) ? value : null;
return UntilQuote(ref position, out var value) || WhileMemberName(ref position, out value) ? value : null;
}
private bool TryBoolean(int position, out bool value)
@ -551,7 +548,7 @@ namespace PSRule.Runtime.ObjectPath
private bool TryInteger(int position, out int value)
{
value = default;
return WhileNumeric(position, out int end) && int.TryParse(Substring(position, end), out value);
return WhileNumeric(position, out var end) && int.TryParse(Substring(position, end), out value);
}
private bool IsSequence(int position, string sequence)

Просмотреть файл

@ -167,7 +167,7 @@ namespace PSRule.Runtime.ObjectPath
public bool Consume(PathTokenType type)
{
return Peak(out IPathToken token) && token.Type == type && Next();
return Peak(out var token) && token.Type == type && Next();
}
public bool Next(out IPathToken token)

Просмотреть файл

@ -138,7 +138,7 @@ namespace PSRule.Runtime
return new PSObject[] { sourceObject };
var cacheKey = sourceObject.BaseObject.ToString();
if (GetContext().Pipeline.ContentCache.TryGetValue(cacheKey, out PSObject[] result))
if (GetContext().Pipeline.ContentCache.TryGetValue(cacheKey, out var result))
return result;
var items = PipelineReceiverActions.DetectInputFormat(new TargetObject(sourceObject), PipelineReceiverActions.PassThru).ToArray();
@ -156,13 +156,13 @@ namespace PSRule.Runtime
public PSObject[] GetContentField(PSObject sourceObject, string field)
{
var content = GetContent(sourceObject);
if (content == null || content.Length == 0 || string.IsNullOrEmpty(field))
if (IsEmptyContent(content) || string.IsNullOrEmpty(field))
return Array.Empty<PSObject>();
var result = new List<PSObject>();
for (var i = 0; i < content.Length; i++)
{
if (ObjectHelper.GetPath(content[i], field, false, out object value) && value != null)
if (ObjectHelper.GetPath(content[i], field, false, out var value) && value != null)
{
if (value is IEnumerable evalue)
{
@ -183,10 +183,12 @@ namespace PSRule.Runtime
public PSObject GetContentFirstOrDefault(PSObject sourceObject)
{
var content = GetContent(sourceObject);
if (content == null || content.Length == 0)
return null;
return IsEmptyContent(content) ? null : content[0];
}
return content[0];
private static bool IsEmptyContent(PSObject[] content)
{
return content == null || content.Length == 0;
}
/// <summary>

Просмотреть файл

@ -37,10 +37,7 @@ namespace PSRule.Runtime
{
get
{
if (Source.Count == 0)
return null;
return Source[0].File;
return Source.Count == 0 ? null : Source[0].File;
}
}

Просмотреть файл

@ -26,7 +26,7 @@ namespace PSRule.Runtime
continue;
var baseObject = GetBaseObject(v);
if (!(TryAssertResult(baseObject, out bool result) || TryBoolean(baseObject, out result)))
if (!(TryAssertResult(baseObject, out var result) || TryBoolean(baseObject, out result)))
{
RunspaceContext.CurrentThread.ErrorInvaildRuleResult();
hasErrors = true;

Просмотреть файл

@ -12,7 +12,6 @@ using System.Text;
using System.Threading;
using PSRule.Configuration;
using PSRule.Definitions;
using PSRule.Definitions.Selectors;
using PSRule.Pipeline;
using PSRule.Resources;
using PSRule.Rules;
@ -178,10 +177,24 @@ namespace PSRule.Runtime
Writer.WriteWarning(PSRuleResources.OutcomeRulePass, RuleRecord.RuleName, Binding.TargetName);
if (_PassStream == OutcomeLogStream.Error && Writer.ShouldWriteError())
Writer.WriteError(new ErrorRecord(new RuleException(string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.OutcomeRulePass, RuleRecord.RuleName, Binding.TargetName)), SOURCE_OUTCOME_PASS, ErrorCategory.InvalidData, null));
Writer.WriteError(new ErrorRecord(
new RuleException(string.Format(
Thread.CurrentThread.CurrentCulture,
PSRuleResources.OutcomeRulePass,
RuleRecord.RuleName,
Binding.TargetName)),
SOURCE_OUTCOME_PASS,
ErrorCategory.InvalidData,
null));
if (_PassStream == OutcomeLogStream.Information && Writer.ShouldWriteInformation())
Writer.WriteInformation(new InformationRecord(messageData: string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.OutcomeRulePass, RuleRecord.RuleName, Binding.TargetName), source: SOURCE_OUTCOME_PASS));
Writer.WriteInformation(new InformationRecord(
messageData: string.Format(
Thread.CurrentThread.CurrentCulture,
PSRuleResources.OutcomeRulePass,
RuleRecord.RuleName,
Binding.TargetName),
source: SOURCE_OUTCOME_PASS));
}
public void Fail()
@ -193,10 +206,24 @@ namespace PSRule.Runtime
Writer.WriteWarning(PSRuleResources.OutcomeRuleFail, RuleRecord.RuleName, Binding.TargetName);
if (_FailStream == OutcomeLogStream.Error && Writer.ShouldWriteError())
Writer.WriteError(new ErrorRecord(new RuleException(string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.OutcomeRuleFail, RuleRecord.RuleName, Binding.TargetName)), SOURCE_OUTCOME_FAIL, ErrorCategory.InvalidData, null));
Writer.WriteError(new ErrorRecord(
new RuleException(string.Format(
Thread.CurrentThread.CurrentCulture,
PSRuleResources.OutcomeRuleFail,
RuleRecord.RuleName,
Binding.TargetName)),
SOURCE_OUTCOME_FAIL,
ErrorCategory.InvalidData,
null));
if (_FailStream == OutcomeLogStream.Information && Writer.ShouldWriteInformation())
Writer.WriteInformation(new InformationRecord(messageData: string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.OutcomeRuleFail, RuleRecord.RuleName, Binding.TargetName), source: SOURCE_OUTCOME_FAIL));
Writer.WriteInformation(new InformationRecord(
messageData: string.Format(
Thread.CurrentThread.CurrentCulture,
PSRuleResources.OutcomeRuleFail,
RuleRecord.RuleName,
Binding.TargetName),
source: SOURCE_OUTCOME_FAIL));
}
public void WarnRuleInconclusive(string ruleId)
@ -282,7 +309,10 @@ namespace PSRule.Runtime
return;
Writer.WriteError(new ErrorRecord(
exception: new RuleException(message: string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.InvalidRuleResult, RuleBlock.RuleId)),
exception: new RuleException(message: string.Format(
Thread.CurrentThread.CurrentCulture,
PSRuleResources.InvalidRuleResult,
RuleBlock.RuleId)),
errorId: ERRORID_INVALIDRULERESULT,
errorCategory: ErrorCategory.InvalidResult,
targetObject: null
@ -319,7 +349,12 @@ namespace PSRule.Runtime
if (Writer == null || !Writer.ShouldWriteVerbose())
return;
Writer.WriteVerbose(string.Concat(GetLogPrefix(), "[", condition, "] -- ", string.Format(Thread.CurrentThread.CurrentCulture, message, args)));
Writer.WriteVerbose(string.Concat(
GetLogPrefix(),
"[",
condition,
"] -- ",
string.Format(Thread.CurrentThread.CurrentCulture, message, args)));
}
public void VerboseConditionResult(string condition, int pass, int count, bool outcome)
@ -493,26 +528,29 @@ namespace PSRule.Runtime
private string GetStackTrace(ErrorRecord record)
{
if (RuleBlock == null)
return record.ScriptStackTrace;
return string.Concat(
record.ScriptStackTrace,
Environment.NewLine,
string.Format(Thread.CurrentThread.CurrentCulture, PSRuleResources.RuleStackTrace, RuleBlock.RuleName, RuleBlock.Extent.File, RuleBlock.Extent.StartLineNumber)
);
return RuleBlock == null
? record.ScriptStackTrace
: string.Concat(
record.ScriptStackTrace,
Environment.NewLine,
string.Format(
Thread.CurrentThread.CurrentCulture,
PSRuleResources.RuleStackTrace,
RuleBlock.RuleName,
RuleBlock.Extent.File,
RuleBlock.Extent.StartLineNumber)
);
}
private string GetErrorId(ErrorRecord record)
{
if (RuleBlock == null)
return record.FullyQualifiedErrorId;
return string.Concat(
record.FullyQualifiedErrorId,
",",
RuleBlock.RuleName
);
return RuleBlock == null
? record.FullyQualifiedErrorId
: string.Concat(
record.FullyQualifiedErrorId,
",",
RuleBlock.RuleName
);
}
private static string GetPositionMessage(ErrorRecord errorRecord)
@ -546,10 +584,7 @@ namespace PSRule.Runtime
return 0;
var lines = positionMessage.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length != 3)
return 0;
return lines[2].LastIndexOf('~') - 1;
return lines.Length != 3 ? 0 : lines[2].LastIndexOf('~') - 1;
}
private string GetLogPrefix()
@ -608,11 +643,11 @@ namespace PSRule.Runtime
public bool TrySelector(string name)
{
name = ResourceHelper.GetIdString(Source.File.ModuleName, name);
if (TargetObject == null || Pipeline == null || !Pipeline.Selector.TryGetValue(name, out SelectorVisitor selector))
if (TargetObject == null || Pipeline == null || !Pipeline.Selector.TryGetValue(name, out var selector))
return false;
var annotation = TargetObject.GetAnnotation<SelectorTargetAnnotation>();
if (annotation.TryGetSelectorResult(selector, out bool result))
if (annotation.TryGetSelectorResult(selector, out var result))
return result;
result = selector.Match(TargetObject.Value);
@ -680,7 +715,7 @@ namespace PSRule.Runtime
internal void AddService(string id, object service)
{
ResourceHelper.ParseIdString(_LanguageScopes.Current.Name, id, out string scopeName, out string name);
ResourceHelper.ParseIdString(_LanguageScopes.Current.Name, id, out var scopeName, out var name);
if (!StringComparer.OrdinalIgnoreCase.Equals(_LanguageScopes.Current.Name, scopeName))
return;
@ -689,16 +724,13 @@ namespace PSRule.Runtime
internal object GetService(string id)
{
ResourceHelper.ParseIdString(_LanguageScopes.Current.Name, id, out string scopeName, out string name);
if (!_LanguageScopes.TryScope(scopeName, out ILanguageScope scope))
return null;
return scope.GetService(name);
ResourceHelper.ParseIdString(_LanguageScopes.Current.Name, id, out var scopeName, out var name);
return !_LanguageScopes.TryScope(scopeName, out var scope) ? null : scope.GetService(name);
}
private void RunConventionInitialize()
{
if (_Conventions == null || _Conventions.Count == 0)
if (IsEmptyConventions())
return;
for (var i = 0; i < _Conventions.Count; i++)
@ -707,7 +739,7 @@ namespace PSRule.Runtime
private void RunConventionBegin()
{
if (_Conventions == null || _Conventions.Count == 0)
if (IsEmptyConventions())
return;
for (var i = 0; i < _Conventions.Count; i++)
@ -716,7 +748,7 @@ namespace PSRule.Runtime
private void RunConventionProcess()
{
if (_Conventions == null || _Conventions.Count == 0)
if (IsEmptyConventions())
return;
for (var i = 0; i < _Conventions.Count; i++)
@ -725,13 +757,18 @@ namespace PSRule.Runtime
private void RunConventionEnd()
{
if (_Conventions == null || _Conventions.Count == 0)
if (IsEmptyConventions())
return;
for (var i = 0; i < _Conventions.Count; i++)
_Conventions[i].End(this, null);
}
private bool IsEmptyConventions()
{
return _Conventions == null || _Conventions.Count == 0;
}
public void WriteReason(string text)
{
if (string.IsNullOrEmpty(text) || !IsScope(RunspaceScope.Rule))
@ -759,7 +796,12 @@ namespace PSRule.Runtime
{
Pipeline.Begin(this);
var builder = new TargetBinderBuilder(Pipeline.BindTargetName, Pipeline.BindTargetType, Pipeline.BindField, Pipeline.Option.Input.TargetType);
var builder = new TargetBinderBuilder(
Pipeline.BindTargetName,
Pipeline.BindTargetType,
Pipeline.BindField,
Pipeline.Option.Input.TargetType);
foreach (var languageScope in _LanguageScopes.Get())
{
var targetBinding = Pipeline.Baseline.GetTargetBinding();

Просмотреть файл

@ -31,10 +31,7 @@ namespace PSRule.Runtime
internal RunspaceContext GetContext()
{
if (_Context == null)
return RunspaceContext.CurrentThread;
return _Context;
return _Context ?? RunspaceContext.CurrentThread;
}
#endregion Helper methods

Просмотреть файл

@ -251,10 +251,7 @@ namespace PSRule.Runtime
private bool GuardPRID(PR prid)
{
if (_IncludePrerelease)
return false;
return Stable && !IsStable(prid);
return !_IncludePrerelease && Stable && !IsStable(prid);
}
private bool EQ(int major, int minor, int patch, PR prid)
@ -288,10 +285,9 @@ namespace PSRule.Runtime
/// </summary>
private bool GT(int major, int minor, int patch, PR prid)
{
if (!IsStable(prid) && !_IncludePrerelease)
return EQCore(major, minor, patch) && PR(prid) < 0;
return GTCore(major, minor, patch) || (EQCore(major, minor, patch) && PR(prid) < 0);
return !IsStable(prid) && !_IncludePrerelease
? EQCore(major, minor, patch) && PR(prid) < 0
: GTCore(major, minor, patch) || (EQCore(major, minor, patch) && PR(prid) < 0);
}
/// <summary>
@ -299,10 +295,9 @@ namespace PSRule.Runtime
/// </summary>
private bool LT(int major, int minor, int patch, PR prid)
{
if (!IsStable(prid) && !_IncludePrerelease)
return EQCore(major, minor, patch) && PR(prid) > 0;
return LTCore(major, minor, patch) || (EQCore(major, minor, patch) && PR(prid) > 0);
return !IsStable(prid) && !_IncludePrerelease
? EQCore(major, minor, patch) && PR(prid) > 0
: LTCore(major, minor, patch) || (EQCore(major, minor, patch) && PR(prid) > 0);
}
/// <summary>
@ -417,10 +412,10 @@ namespace PSRule.Runtime
{
var leftNumeric = false;
var rightNumeric = false;
if (long.TryParse(left[i], out long l))
if (long.TryParse(left[i], out var l))
leftNumeric = true;
if (long.TryParse(right[i], out long r))
if (long.TryParse(right[i], out var r))
rightNumeric = true;
if (leftNumeric != rightNumeric)
@ -548,7 +543,7 @@ namespace PSRule.Runtime
if (!IsAllowedChar(_Current))
return false;
if (TryDigit(out int digit))
if (TryDigit(out var digit))
segments[segmentIndex++] = digit;
if (IsSeparator(_Current))
@ -580,7 +575,7 @@ namespace PSRule.Runtime
if (EOF)
return false;
bool numeric = true;
var numeric = true;
while (!EOF && IsPrereleaseChar(_Current, ref numeric))
Next();
@ -710,17 +705,17 @@ namespace PSRule.Runtime
return true;
var stream = new VersionStream(value);
stream.Flags(out ConstraintFlags flags);
stream.Flags(out var flags);
if (flags.HasFlag(ConstraintFlags.Prerelease))
includePrerelease = true;
while (!stream.EOF)
{
stream.Operator(out ComparisonOperatorFlags comparison);
if (!stream.TrySegments(out int[] segments))
stream.Operator(out var comparison);
if (!stream.TrySegments(out var segments))
return false;
stream.Prerelease(out PR prerelease);
stream.Prerelease(out var prerelease);
stream.Build(out _);
c.Join(segments[0], segments[1], segments[2], prerelease, comparison, stream.GetJoin(), includePrerelease);
@ -735,13 +730,13 @@ namespace PSRule.Runtime
return false;
var stream = new VersionStream(value);
if (!stream.TrySegments(out int[] segments))
if (!stream.TrySegments(out var segments))
return false;
if (!stream.Prerelease(out PR prerelease))
if (!stream.Prerelease(out var prerelease))
return false;
stream.Build(out string build);
stream.Build(out var build);
version = new Version(segments[0], segments[1], segments[2], prerelease, build);
return true;
}

Просмотреть файл

@ -70,10 +70,7 @@ namespace PSRule
private PSRuleOption GetOption(string path = null)
{
if (path == null)
return new PSRuleOption();
return PSRuleOption.FromFile(path);
return path == null ? new PSRuleOption() : PSRuleOption.FromFile(path);
}
private static string GetSourcePath(string fileName)

Просмотреть файл

@ -44,8 +44,8 @@ namespace PSRule
Assert.Equal(2, actual[1].Value.PropertyValue("spec").PropertyValue("properties").PropertyValue<int>("value2"));
Assert.Equal(3, actual[1].Value.PropertyValue("spec").PropertyValue("properties").PropertyValue<PSObject[]>("array").Length);
Assert.Equal("TestObject1", PipelineHookActions.BindTargetName(null, false, false, actual[0].Value));
actual[0].Value.TryTargetInfo(out Runtime.PSRuleTargetInfo info1);
actual[1].Value.TryTargetInfo(out Runtime.PSRuleTargetInfo info2);
actual[0].Value.TryTargetInfo(out var info1);
actual[1].Value.TryTargetInfo(out var info2);
Assert.Equal("some-file.json", info1.Source[0].File);
Assert.NotNull(info2.Source[0]);

Просмотреть файл

@ -111,10 +111,7 @@ namespace PSRule
private PSRuleOption GetOption(string path = null)
{
if (path == null)
return new PSRuleOption();
return PSRuleOption.FromFile(path);
return path == null ? new PSRuleOption() : PSRuleOption.FromFile(path);
}
private static string GetSourcePath(string fileName)

Просмотреть файл

@ -11,7 +11,7 @@ namespace PSRule
[Fact]
public void ParseIdString()
{
ResourceHelper.ParseIdString(null, "Module1\\Resource1", out string moduleName, out string name);
ResourceHelper.ParseIdString(null, "Module1\\Resource1", out var moduleName, out var name);
Assert.Equal("Module1", moduleName);
Assert.Equal("Resource1", name);

Просмотреть файл

@ -96,14 +96,7 @@ The latest tag automatically uses imagePullPolicy: Always instead of the default
{
var reader = new MarkdownReader(yamlHeaderOnly: false);
var content = GetMarkdownContent();
if (nx)
{
content = content.Replace("\r\n", "\n");
}
else
{
content = content.Replace("\r\n", "\n").Replace("\n", "\r\n");
}
content = nx ? content.Replace("\r\n", "\n") : content.Replace("\r\n", "\n").Replace("\n", "\r\n");
return reader.Read(content, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RuleDocument.md"));
}

Просмотреть файл

@ -83,7 +83,7 @@ namespace PSRule
Assert.False(equals.Match(actual4));
// With name
var withName = GetSelectorVisitor("YamlNameEquals", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameEquals", out var context);
var actual5 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -142,7 +142,7 @@ namespace PSRule
Assert.False(notEquals.Match(actual4));
// With name
var withName = GetSelectorVisitor("YamlNameNotEquals", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameNotEquals", out var context);
var actual5 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -175,7 +175,7 @@ namespace PSRule
Assert.True(hasValueFalse.Match(actual3));
// With name
var withName = GetSelectorVisitor("YamlNameHasValue", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameHasValue", out var context);
var actual4 = GetObject();
context.EnterTargetObject(new TargetObject(actual4));
@ -199,7 +199,7 @@ namespace PSRule
Assert.False(match.Match(actual5));
// With name
var withName = GetSelectorVisitor("YamlNameMatch", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameMatch", out var context);
var actual6 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -229,7 +229,7 @@ namespace PSRule
Assert.True(notMatch.Match(actual4));
// With name
var withName = GetSelectorVisitor("YamlNameNotMatch", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameNotMatch", out var context);
var actual6 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -263,7 +263,7 @@ namespace PSRule
Assert.False(@in.Match(actual6));
// With name
var withName = GetSelectorVisitor("YamlNameIn", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameIn", out var context);
var actual7 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -295,7 +295,7 @@ namespace PSRule
Assert.True(notIn.Match(actual5));
// With name
var withName = GetSelectorVisitor("YamlNameNotIn", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameNotIn", out var context);
var actual6 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -408,7 +408,7 @@ namespace PSRule
Assert.True(less.Match(actual7));
// With name
var withName = GetSelectorVisitor("YamlNameLess", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameLess", out var context);
var actual8 = GetObject(
(name: "Name", value: "ItemTwo")
);
@ -444,7 +444,7 @@ namespace PSRule
Assert.True(lessOrEquals.Match(actual7));
// With name
var withName = GetSelectorVisitor("YamlNameLessOrEquals", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameLessOrEquals", out var context);
var actual8 = GetObject(
(name: "Name", value: "ItemTwo")
);
@ -480,7 +480,7 @@ namespace PSRule
Assert.False(greater.Match(actual7));
// With name
var withName = GetSelectorVisitor("YamlNameGreater", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameGreater", out var context);
var actual8 = GetObject(
(name: "Name", value: "ItemTwo")
);
@ -516,7 +516,7 @@ namespace PSRule
Assert.False(greaterOrEquals.Match(actual7));
// With name
var withName = GetSelectorVisitor("YamlNameGreaterOrEquals", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameGreaterOrEquals", out var context);
var actual8 = GetObject(
(name: "Name", value: "ItemTwo")
);
@ -550,7 +550,7 @@ namespace PSRule
Assert.False(startsWith.Match(actual6));
// With name
var withName = GetSelectorVisitor("YamlNameStartsWith", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameStartsWith", out var context);
var actual7 = GetObject(
(name: "Name", value: "1TargetObject")
);
@ -584,7 +584,7 @@ namespace PSRule
Assert.False(endsWith.Match(actual6));
// With name
var withName = GetSelectorVisitor("YamlNameEndsWith", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameEndsWith", out var context);
var actual7 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -618,7 +618,7 @@ namespace PSRule
Assert.False(contains.Match(actual6));
// With name
var withName = GetSelectorVisitor("YamlNameContains", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameContains", out var context);
var actual7 = GetObject(
(name: "Name", value: "Target.1.Object")
);
@ -659,7 +659,7 @@ namespace PSRule
Assert.False(isStringFalse.Match(actual5));
// With name
var withName = GetSelectorVisitor("YamlNameIsString", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameIsString", out var context);
var actual7 = GetObject(
(name: "Name", value: "TargetObject1")
);
@ -703,7 +703,7 @@ namespace PSRule
Assert.False(isLowerTrue.Match(actual6));
// With name
var withName = GetSelectorVisitor("YamlNameIsLower", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameIsLower", out var context);
var actual7 = GetObject(
(name: "Name", value: "targetobject1")
);
@ -747,7 +747,7 @@ namespace PSRule
Assert.False(isUpperFalse.Match(actual6));
// With name
var withName = GetSelectorVisitor("YamlNameIsUpper", out RunspaceContext context);
var withName = GetSelectorVisitor("YamlNameIsUpper", out var context);
var actual7 = GetObject(
(name: "Name", value: "TARGETOBJECT1")
);
@ -924,7 +924,7 @@ namespace PSRule
[Fact]
public void Type()
{
var equals = GetSelectorVisitor("YamlTypeEquals", out RunspaceContext context);
var equals = GetSelectorVisitor("YamlTypeEquals", out var context);
var actual1 = GetObject();
actual1.TypeNames.Insert(0, "CustomType1");
@ -936,7 +936,7 @@ namespace PSRule
[Fact]
public void Name()
{
var equals = GetSelectorVisitor("YamlNameEquals", out RunspaceContext context);
var equals = GetSelectorVisitor("YamlNameEquals", out var context);
var actual1 = GetObject(
(name: "Name", value: "TargetObject1")
);

Просмотреть файл

@ -10,20 +10,20 @@ namespace PSRule
[Fact]
public void Version()
{
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-alpha.3+7223b39", out Runtime.SemanticVersion.Version actual1));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-alpha.3+7223b39", out var actual1));
Assert.Equal(1, actual1.Major);
Assert.Equal(2, actual1.Minor);
Assert.Equal(3, actual1.Patch);
Assert.Equal("alpha.3", actual1.Prerelease.Value);
Assert.Equal("7223b39", actual1.Build);
Assert.True(Runtime.SemanticVersion.TryParseVersion("v1.2.3-alpha.3", out Runtime.SemanticVersion.Version actual2));
Assert.True(Runtime.SemanticVersion.TryParseVersion("v1.2.3-alpha.3", out var actual2));
Assert.Equal(1, actual2.Major);
Assert.Equal(2, actual2.Minor);
Assert.Equal(3, actual2.Patch);
Assert.Equal("alpha.3", actual2.Prerelease.Value);
Assert.True(Runtime.SemanticVersion.TryParseVersion("v1.2.3+7223b39", out Runtime.SemanticVersion.Version actual3));
Assert.True(Runtime.SemanticVersion.TryParseVersion("v1.2.3+7223b39", out var actual3));
Assert.Equal(1, actual3.Major);
Assert.Equal(2, actual3.Minor);
Assert.Equal(3, actual3.Patch);
@ -34,37 +34,37 @@ namespace PSRule
public void Constraint()
{
// Versions
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3", out Runtime.SemanticVersion.Version version1));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-alpha.3+7223b39", out Runtime.SemanticVersion.Version version2));
Assert.True(Runtime.SemanticVersion.TryParseVersion("3.4.5-alpha.9", out Runtime.SemanticVersion.Version version3));
Assert.True(Runtime.SemanticVersion.TryParseVersion("3.4.5", out Runtime.SemanticVersion.Version version4));
Assert.False(Runtime.SemanticVersion.TryParseVersion("1.2.3-", out Runtime.SemanticVersion.Version _));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-0", out Runtime.SemanticVersion.Version _));
Assert.False(Runtime.SemanticVersion.TryParseVersion("1.2.3-0123", out Runtime.SemanticVersion.Version _));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-0A", out Runtime.SemanticVersion.Version _));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3", out var version1));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-alpha.3+7223b39", out var version2));
Assert.True(Runtime.SemanticVersion.TryParseVersion("3.4.5-alpha.9", out var version3));
Assert.True(Runtime.SemanticVersion.TryParseVersion("3.4.5", out var version4));
Assert.False(Runtime.SemanticVersion.TryParseVersion("1.2.3-", out var _));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-0", out var _));
Assert.False(Runtime.SemanticVersion.TryParseVersion("1.2.3-0123", out var _));
Assert.True(Runtime.SemanticVersion.TryParseVersion("1.2.3-0A", out var _));
// Constraints
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3", out Runtime.SemanticVersion.IConstraint actual1));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3-alpha.3", out Runtime.SemanticVersion.IConstraint actual2));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">1.2.3-alpha.3", out Runtime.SemanticVersion.IConstraint actual3));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">1.2.3-alpha.1", out Runtime.SemanticVersion.IConstraint actual4));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<1.2.3-beta", out Runtime.SemanticVersion.IConstraint actual5));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("^1.2.3-alpha", out Runtime.SemanticVersion.IConstraint actual6));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<3.4.6", out Runtime.SemanticVersion.IConstraint actual7));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("=v1.2.3", out Runtime.SemanticVersion.IConstraint actual8));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">=v1.2.3", out Runtime.SemanticVersion.IConstraint actual9));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">=v1.2.3-0", out Runtime.SemanticVersion.IConstraint actual10));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<3.4.5", out Runtime.SemanticVersion.IConstraint actual11));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<3.4.5-9999999999", out Runtime.SemanticVersion.IConstraint actual12));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("^1.0.0", out Runtime.SemanticVersion.IConstraint actual13));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<1.2.3-0", out Runtime.SemanticVersion.IConstraint actual14));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3|| >=3.4.5-0 3.4.5", out Runtime.SemanticVersion.IConstraint actual15));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3 ||>=3.4.5-0 || 3.4.5", out Runtime.SemanticVersion.IConstraint actual16));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3||3.4.5", out Runtime.SemanticVersion.IConstraint actual17));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">=1.2.3", out Runtime.SemanticVersion.IConstraint actual18, includePrerelease: true));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<=3.4.5-0", out Runtime.SemanticVersion.IConstraint actual19, includePrerelease: true));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("@pre >=1.2.3", out Runtime.SemanticVersion.IConstraint actual20));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("@prerelease <=3.4.5-0", out Runtime.SemanticVersion.IConstraint actual21));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3", out var actual1));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3-alpha.3", out var actual2));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">1.2.3-alpha.3", out var actual3));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">1.2.3-alpha.1", out var actual4));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<1.2.3-beta", out var actual5));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("^1.2.3-alpha", out var actual6));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<3.4.6", out var actual7));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("=v1.2.3", out var actual8));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">=v1.2.3", out var actual9));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">=v1.2.3-0", out var actual10));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<3.4.5", out var actual11));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<3.4.5-9999999999", out var actual12));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("^1.0.0", out var actual13));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<1.2.3-0", out var actual14));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3|| >=3.4.5-0 3.4.5", out var actual15));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3 ||>=3.4.5-0 || 3.4.5", out var actual16));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("1.2.3||3.4.5", out var actual17));
Assert.True(Runtime.SemanticVersion.TryParseConstraint(">=1.2.3", out var actual18, includePrerelease: true));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("<=3.4.5-0", out var actual19, includePrerelease: true));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("@pre >=1.2.3", out var actual20));
Assert.True(Runtime.SemanticVersion.TryParseConstraint("@prerelease <=3.4.5-0", out var actual21));
// Version1 - 1.2.3
Assert.True(actual1.Equals(version1));