Formatting: Add Missing Braces Back

This commit is contained in:
Gabe Stocco 2023-03-02 11:45:11 -08:00
Родитель a73ed505c1
Коммит d6dc1fc5a7
25 изменённых файлов: 503 добавлений и 68 удалений

228
.editorconfig Normal file
Просмотреть файл

@ -0,0 +1,228 @@
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
# C# files
[*.cs]
#### Core EditorConfig Options ####
# Indentation and spacing
indent_size = 4
indent_style = space
tab_width = 4
# New line preferences
end_of_line = crlf
insert_final_newline = false
#### .NET Coding Conventions ####
# Organize usings
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = false
file_header_template = unset
# this. and Me. preferences
dotnet_style_qualification_for_event = false:warning
dotnet_style_qualification_for_field = false
dotnet_style_qualification_for_method = false:warning
dotnet_style_qualification_for_property = false:warning
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:warning
dotnet_style_predefined_type_for_member_access = true:warning
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity
dotnet_style_parentheses_in_other_operators = never_if_unnecessary
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members
# Expression-level preferences
dotnet_style_coalesce_expression = true
dotnet_style_collection_initializer = true
dotnet_style_explicit_tuple_names = true
dotnet_style_namespace_match_folder = true
dotnet_style_null_propagation = true
dotnet_style_object_initializer = true
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true:warning
dotnet_style_prefer_compound_assignment = true
dotnet_style_prefer_conditional_expression_over_assignment = true
dotnet_style_prefer_conditional_expression_over_return = true
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
dotnet_style_prefer_inferred_anonymous_type_member_names = true
dotnet_style_prefer_inferred_tuple_names = true
dotnet_style_prefer_is_null_check_over_reference_equality_method = true
dotnet_style_prefer_simplified_boolean_expressions = true
dotnet_style_prefer_simplified_interpolation = true
# Field preferences
dotnet_style_readonly_field = true
# Parameter preferences
dotnet_code_quality_unused_parameters = all
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
# New line preferences
dotnet_style_allow_multiple_blank_lines_experimental = false
dotnet_style_allow_statement_immediately_after_block_experimental = false
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere = false:warning
csharp_style_var_for_built_in_types = false:warning
csharp_style_var_when_type_is_apparent = false:warning
# Expression-bodied members
csharp_style_expression_bodied_accessors = true
csharp_style_expression_bodied_constructors = false
csharp_style_expression_bodied_indexers = true
csharp_style_expression_bodied_lambdas = true
csharp_style_expression_bodied_local_functions = false
csharp_style_expression_bodied_methods = false
csharp_style_expression_bodied_operators = when_on_single_line
csharp_style_expression_bodied_properties = true
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true
csharp_style_pattern_matching_over_is_with_cast_check = true
csharp_style_prefer_extended_property_pattern = true
csharp_style_prefer_not_pattern = true
csharp_style_prefer_pattern_matching = true:suggestion
csharp_style_prefer_switch_expression = true
# Null-checking preferences
csharp_style_conditional_delegate_call = true
# Modifier preferences
csharp_prefer_static_local_function = true
csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async
csharp_style_prefer_readonly_struct = true
# Code-block preferences
csharp_prefer_braces = true:warning
csharp_prefer_simple_using_statement = true:warning
csharp_style_namespace_declarations = block_scoped:warning
csharp_style_prefer_method_group_conversion = true:warning
csharp_style_prefer_top_level_statements = false:warning
# Expression-level preferences
csharp_prefer_simple_default_expression = true
csharp_style_deconstructed_variable_declaration = true
csharp_style_implicit_object_creation_when_type_is_apparent = true
csharp_style_inlined_variable_declaration = true
csharp_style_prefer_index_operator = true
csharp_style_prefer_local_over_anonymous_function = true
csharp_style_prefer_null_check_over_type_check = true
csharp_style_prefer_range_operator = true
csharp_style_prefer_tuple_swap = true
csharp_style_prefer_utf8_string_literals = true
csharp_style_throw_expression = true
csharp_style_unused_value_assignment_preference = discard_variable
csharp_style_unused_value_expression_statement_preference = discard_variable
# 'using' directive preferences
csharp_using_directive_placement = inside_namespace:suggestion
# New line preferences
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false
csharp_style_allow_embedded_statements_on_same_line_experimental = true
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_catch = true
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case

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

@ -18,9 +18,11 @@ public class DistinctBenchmarks
SortedDictionary<string, string> uniqueTags = new();
List<string> outList = new();
foreach (var r in ruleSet)
{
//builds a list of unique tags
foreach (var t in (IList<string>?)r?.Tags ?? Array.Empty<string>())
if (uniqueTags.ContainsKey(t))
foreach (var t in (IList<string>?)r?.Tags ?? Array.Empty<string>())
{
if (uniqueTags.ContainsKey(t))
{
continue;
}
@ -28,9 +30,14 @@ public class DistinctBenchmarks
{
uniqueTags.Add(t, t);
}
}
}
//generate results list
foreach (var s in uniqueTags.Values) outList.Add(s);
foreach (var s in uniqueTags.Values)
{
outList.Add(s);
}
return outList;
}
@ -40,9 +47,13 @@ public class DistinctBenchmarks
{
HashSet<string> hashSet = new();
foreach (var r in ruleSet)
{
//builds a list of unique tags
foreach (var t in (IList<string>?)r?.Tags ?? Array.Empty<string>())
hashSet.Add(t);
foreach (var t in (IList<string>?)r?.Tags ?? Array.Empty<string>())
{
hashSet.Add(t);
}
}
var theList = hashSet.ToList();
theList.Sort();

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

@ -335,7 +335,10 @@ public static class Program
done = true;
});
while (!done) Thread.Sleep(100);
while (!done)
{
Thread.Sleep(100);
}
pbar.ObservedError = !initialSuccess;
pbar.Message = !initialSuccess

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

@ -111,7 +111,9 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
//add summary values for sorted tags lists of taginfo
foreach (var outerKey in KeyedSortedTagInfoLists.Keys)
{
hashData.Add(outerKey, KeyedSortedTagInfoLists[outerKey]);
}
hashData["cputargets"] = _appMetaData?.CPUTargets;
hashData["apptypes"] = _appMetaData?.AppTypes ?? new List<string>();
@ -212,7 +214,10 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
private void SafeList(List<string>? valuesList)
{
for (var i = 0; i < valuesList?.Count; i++) valuesList[i] = SafeString(valuesList[i]);
for (var i = 0; i < valuesList?.Count; i++)
{
valuesList[i] = SafeString(valuesList[i]);
}
}
private string SafeString(string? value)
@ -260,7 +265,8 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
//for each preferred group of tag patterns determine if at least one instance was detected
foreach (var tagCategory in TagGroupPreferences ?? new List<TagCategory>())
foreach (var tagGroup in tagCategory.Groups ?? new List<TagGroup>())
{
foreach (var tagGroup in tagCategory.Groups ?? new List<TagGroup>())
{
if (string.IsNullOrEmpty(tagGroup.Title))
{
@ -296,6 +302,7 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
}
}
}
}
//create simple ranked page lists HTML use
KeyedSortedTagInfoLists["tagGrpAllTagsByConfidence"] = GetTagInfoListByConfidence();
@ -313,14 +320,19 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
List<TagGroup> result = new();
//get all tag groups for specified category
foreach (var categoryTagGroup in TagGroupPreferences ?? new List<TagCategory>())
{
if (categoryTagGroup.Name == category)
{
result = categoryTagGroup.Groups ?? new List<TagGroup>();
break;
}
}
//now get all matches for that group i.e. Authentication
foreach (var group in result) GetTagInfoListByTagGroup(group);
foreach (var group in result)
{
GetTagInfoListByTagGroup(group);
}
return result;
}
@ -334,8 +346,12 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
HashSet<string> results = new();
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
foreach (var tag in match.Tags ?? Array.Empty<string>())
results.Add(tag);
{
foreach (var tag in match.Tags ?? Array.Empty<string>())
{
results.Add(tag);
}
}
return results;
}
@ -353,14 +369,17 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
HashSet<string> hashSet = new();
foreach (var pattern in tagGroup.Patterns ?? new List<TagSearchPattern>())
{
if (pattern.Detected) //set at program.RollUp already so don't search for again
{
var tagPatternRegex = pattern.Expression;
if (_appMetaData?.TotalMatchesCount > 0)
{
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
foreach (var tagItem in match.Tags ?? Array.Empty<string>())
if (tagPatternRegex.IsMatch(tagItem))
{
foreach (var tagItem in match.Tags ?? Array.Empty<string>())
{
if (tagPatternRegex.IsMatch(tagItem))
{
if (!hashSet.Contains(pattern.SearchPattern))
{
@ -382,7 +401,8 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
{
//ensure we get highest confidence, severity as there are likely multiple matches for this tag pattern
foreach (var updateItem in result)
if (updateItem.Tag == tagItem)
{
if (updateItem.Tag == tagItem)
{
Confidence oldConfidence;
Enum.TryParse(updateItem.Confidence, out oldConfidence);
@ -402,12 +422,16 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
break;
}
}
}
}
}
}
}
}
else
{
foreach (var tagItem in _appMetaData?.UniqueTags ?? new List<string>())
{
if (tagPatternRegex.IsMatch(tagItem) && !hashSet.Contains(pattern.SearchPattern))
{
result.Add(new TagInfo
@ -420,6 +444,7 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
hashSet.Add(tagItem);
}
}
}
}
else if (addNotFound) //allow to report on false presense items
@ -438,6 +463,7 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
result.Add(tagInfo);
hashSet.Add(tagInfo.Tag);
}
}
return result;
}
@ -454,13 +480,16 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
HashSet<string> hashSet = new();
foreach (var pattern in tagGroup.Patterns ?? new List<TagSearchPattern>())
{
if (pattern.Detected)
{
var tagPatternRegex = pattern.Expression;
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
foreach (var tagItem in match.Tags ?? Array.Empty<string>())
if (tagPatternRegex.IsMatch(tagItem))
{
foreach (var tagItem in match.Tags ?? Array.Empty<string>())
{
if (tagPatternRegex.IsMatch(tagItem))
{
if (!hashSet.Contains(tagItem))
{
@ -480,7 +509,8 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
{
//ensure we have highest confidence, severity as there are likly multiple matches for this tag pattern
foreach (var updateItem in result)
if (updateItem.Tag == tagItem)
{
if (updateItem.Tag == tagItem)
{
Confidence oldConfidence;
Enum.TryParse(updateItem.Confidence, out oldConfidence);
@ -500,9 +530,13 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
break;
}
}
}
}
}
}
}
}
}
return result;
}
@ -517,11 +551,14 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
List<TagInfo> result = new();
foreach (var tag in _appMetaData?.UniqueTags ?? new List<string>())
{
if (_appMetaData?.TotalMatchesCount > 0)
{
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
foreach (var testTag in match.Tags ?? Array.Empty<string>())
if (tag == testTag)
{
foreach (var testTag in match.Tags ?? Array.Empty<string>())
{
if (tag == testTag)
{
if (dupCheck.Add(testTag))
{
@ -536,6 +573,8 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
break;
}
}
}
}
}
else
{
@ -545,6 +584,7 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
ShortTag = tag[(tag.LastIndexOf('.') + 1)..]
});
}
}
return result;
}
@ -563,9 +603,12 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
{
var searchPattern = new Regex(tag, RegexOptions.IgnoreCase);
foreach (var confidence in confidences)
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
foreach (var testTag in match.Tags ?? Array.Empty<string>())
if (searchPattern.IsMatch(testTag))
{
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
{
foreach (var testTag in match.Tags ?? Array.Empty<string>())
{
if (searchPattern.IsMatch(testTag))
{
if (match.Confidence == confidence && dupCheck.Add(tag))
{
@ -578,6 +621,9 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
});
}
}
}
}
}
}
return result;
@ -598,9 +644,12 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
{
var searchPattern = new Regex(tag, RegexOptions.IgnoreCase);
foreach (var severity in severities)
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
foreach (var testTag in match.Tags ?? Array.Empty<string>())
if (searchPattern.IsMatch(testTag))
{
foreach (var match in _appMetaData?.Matches ?? new List<MatchRecord>())
{
foreach (var testTag in match.Tags ?? Array.Empty<string>())
{
if (searchPattern.IsMatch(testTag))
{
if (match.Severity == severity && dupCheck.Add(tag))
{
@ -613,6 +662,9 @@ public class AnalyzeHtmlWriter : CommandResultsWriter
});
}
}
}
}
}
}
return result;

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

@ -26,7 +26,10 @@ internal static class AnalyzeSarifWriterExtensions
return;
}
foreach (var tag in tagsToAdd) tc.Add(tag);
foreach (var tag in tagsToAdd)
{
tc.Add(tag);
}
}
}

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

@ -48,7 +48,10 @@ public class AnalyzeTextWriter : CommandResultsWriter
WriteDependencies(analyzeResult.Metadata);
TextWriter.WriteLine(MakeHeading("Match Details"));
foreach (var match in analyzeResult.Metadata.Matches ?? new List<MatchRecord>()) WriteMatch(match);
foreach (var match in analyzeResult.Metadata.Matches ?? new List<MatchRecord>())
{
WriteMatch(match);
}
if (autoClose)
{
@ -89,7 +92,10 @@ public class AnalyzeTextWriter : CommandResultsWriter
{
StringBuilder build = new();
build.Append(string.Format("[{0}]", header));
for (var i = header.Length; i < COLUMN_MAX; i++) build.Append("-");
for (var i = header.Length; i < COLUMN_MAX; i++)
{
build.Append("-");
}
return build.ToString();
}
@ -130,11 +136,16 @@ public class AnalyzeTextWriter : CommandResultsWriter
TextWriter.WriteLine($"Unique matches: {metaData.UniqueMatchesCount}");
TextWriter.WriteLine(MakeHeading("UniqueTags"));
foreach (var tag in metaData.UniqueTags) TextWriter.WriteLine(tag);
foreach (var tag in metaData.UniqueTags)
{
TextWriter.WriteLine(tag);
}
TextWriter.WriteLine(MakeHeading("Select Counters"));
foreach (var tagCounter in metaData.TagCounters ?? new List<MetricTagCounter>())
{
TextWriter.WriteLine($"Tagname: {tagCounter.Tag}, Count: {tagCounter.Count}");
}
}
public void WriteMatch(MatchRecord match)
@ -171,6 +182,9 @@ public class AnalyzeTextWriter : CommandResultsWriter
TextWriter.WriteLine(MakeHeading("Dependencies"));
foreach (var s in metaData.UniqueDependencies ?? new List<string>()) TextWriter.WriteLine(s);
foreach (var s in metaData.UniqueDependencies ?? new List<string>())
{
TextWriter.WriteLine(s);
}
}
}

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

@ -31,7 +31,10 @@ internal class ExportTagsTextWriter : CommandResultsWriter
{
TextWriter.WriteLine("Results");
foreach (var tag in exportTagsResult.TagsList) TextWriter.WriteLine(tag);
foreach (var tag in exportTagsResult.TagsList)
{
TextWriter.WriteLine(tag);
}
}
else
{

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

@ -39,7 +39,9 @@ public class TagDiffTextWriter : CommandResultsWriter
{
TextWriter.WriteLine("Differences");
foreach (var tagDiff in tagDiffResult.TagDiffList)
{
TextWriter.WriteLine("Tag: {0}, Only found in file: {1}", tagDiff.Tag, tagDiff.Source);
}
}
if (autoClose)

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

@ -40,8 +40,10 @@ internal class VerifyRulesTextWriter : CommandResultsWriter
{
TextWriter.WriteLine("Rule status");
foreach (var ruleStatus in verifyRulesResult.RuleStatusList)
{
TextWriter.WriteLine("Ruleid: {0}, Rulename: {1}, Status: {2}", ruleStatus.RulesId,
ruleStatus.RulesName, ruleStatus.Verified);
}
}
if (autoClose)

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

@ -78,6 +78,7 @@ public abstract class AbstractRuleSet
var clauseNumber = 0;
var expression = new StringBuilder("(");
foreach (var pattern in rule.Patterns)
{
if (GenerateClause(pattern, clauseNumber) is { } clause)
{
clauses.Add(clause);
@ -93,6 +94,7 @@ public abstract class AbstractRuleSet
{
_logger.LogWarning("Clause could not be generated from pattern {pattern}", pattern.Pattern);
}
}
if (clauses.Count > 0)
{
@ -150,6 +152,7 @@ public abstract class AbstractRuleSet
if (m.Success)
{
for (var i = 1; i < m.Groups.Count; i++)
{
if (int.TryParse(m.Groups[i].Value, out var value))
{
argList.Add(value);
@ -158,6 +161,7 @@ public abstract class AbstractRuleSet
{
break;
}
}
}
if (argList.Count == 2)

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

@ -141,11 +141,13 @@ public sealed class Languages
if (language != null)
{
foreach (var comment in _comments)
{
if (Array.Exists(comment.Languages ?? new[] { "" },
x => x.Equals(language, StringComparison.InvariantCultureIgnoreCase)) && comment.Inline is { })
{
return comment.Inline;
}
}
}
return result;
@ -163,11 +165,13 @@ public sealed class Languages
if (language != null)
{
foreach (var comment in _comments)
{
if ((comment.Languages?.Contains(language.ToLower(CultureInfo.InvariantCulture)) ?? false) &&
comment.Prefix is { })
{
return comment.Prefix;
}
}
}
return result;
@ -185,11 +189,13 @@ public sealed class Languages
if (language != null)
{
foreach (var comment in _comments)
{
if (Array.Exists(comment.Languages ?? new[] { "" },
x => x.Equals(language, StringComparison.InvariantCultureIgnoreCase)) && comment.Suffix is { })
{
return comment.Suffix;
}
}
}
return result;

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

@ -49,6 +49,7 @@ public class OatRegexWithIndexOperation : OatOperation
else if (clause.Data is List<string> regexList)
{
foreach (var regex in regexList)
{
if (!Helpers.IsValidRegex(regex))
{
yield return new Violation(
@ -56,6 +57,7 @@ public class OatRegexWithIndexOperation : OatOperation
clause.Label ?? rule.Clauses.IndexOf(clause).ToString(CultureInfo.InvariantCulture), regex),
rule, clause);
}
}
}
if (clause.DictData?.Count > 0)
@ -91,6 +93,7 @@ public class OatRegexWithIndexOperation : OatOperation
if (Analyzer != null)
{
foreach (var regexString in RegexList)
{
if (StringToRegex(regexString, regexOpts) is { } regex)
{
if (src.XPaths is not null)
@ -112,7 +115,9 @@ public class OatRegexWithIndexOperation : OatOperation
{
var targets = tc.GetStringFromJsonPath(jsonPath);
foreach (var target in targets)
{
outmatches.AddRange(GetMatches(regex, tc, clause, src.Scopes, target.Item2));
}
}
}
@ -140,6 +145,7 @@ public class OatRegexWithIndexOperation : OatOperation
}
}
}
}
var result = src.Invert ? outmatches.Count == 0 : outmatches.Count > 0;
return new OperationResult(result,
@ -156,6 +162,7 @@ public class OatRegexWithIndexOperation : OatOperation
Boundary? boundary)
{
foreach (var match in regex.Matches(boundary is null ? tc.FullContent : tc.GetBoundaryText(boundary)))
{
if (match is Match m)
{
Boundary translatedBoundary = new()
@ -173,6 +180,7 @@ public class OatRegexWithIndexOperation : OatOperation
yield return (patternIndex, translatedBoundary);
}
}
}
}
/// <summary>

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

@ -192,7 +192,10 @@ public class WithinOperation : OatOperation
}
else
{
foreach (var violation in subOp.ValidationDelegate.Invoke(rule, wc.SubClause)) yield return violation;
foreach (var violation in subOp.ValidationDelegate.Invoke(rule, wc.SubClause))
{
yield return violation;
}
if (wc.SubClause is OatRegexWithIndexClause oatRegexWithIndexClause)
{

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

@ -211,17 +211,22 @@ public class RuleProcessor
// WithinClauses are always ANDed, but each contains all the captures that passed *that* clause.
// We need the captures that passed every clause.
foreach (var aCapture in allCaptured)
{
numberOfInstances.AddOrUpdate(aCapture, 1, (tuple, i) => i + 1);
}
return numberOfInstances.Where(x => x.Value == onlyWithinCaptures.Count).Select(x => x.Key)
.ToList();
}
var outList = new List<(int, Boundary)>();
foreach (var cap in captures)
{
if (cap is TypedClauseCapture<List<(int, Boundary)>> tcc)
{
outList.AddRange(tcc.Result);
}
}
return outList;
}
@ -230,15 +235,21 @@ public class RuleProcessor
List<MatchRecord> removes = new();
foreach (var m in resultsList.Where(x => x.Rule?.Overrides?.Count > 0))
foreach (var idsToOverride in (IList<string>)m.Rule?.Overrides ?? Array.Empty<string>())
// Find all overriden rules and mark them for removal from issues list
foreach (var om in resultsList.FindAll(x => x.Rule?.Id == idsToOverride))
// If the overridden match is a subset of the overriding match
if (om.Boundary.Index >= m.Boundary.Index &&
{
foreach (var idsToOverride in (IList<string>)m.Rule?.Overrides ?? Array.Empty<string>())
{
// Find all overriden rules and mark them for removal from issues list
foreach (var om in resultsList.FindAll(x => x.Rule?.Id == idsToOverride))
{
// If the overridden match is a subset of the overriding match
if (om.Boundary.Index >= m.Boundary.Index &&
om.Boundary.Index <= m.Boundary.Index + m.Boundary.Length)
{
removes.Add(om);
}
}
}
}
// Remove overriden rules
resultsList.RemoveAll(x => removes.Contains(x));
@ -338,7 +349,10 @@ public class RuleProcessor
return resultsList;
}
foreach (var cap in filteredCaptures) resultsList.AddRange(ProcessBoundary(cap));
foreach (var cap in filteredCaptures)
{
resultsList.AddRange(ProcessBoundary(cap));
}
List<MatchRecord> ProcessBoundary(ClauseCapture cap)
{
@ -424,13 +438,17 @@ public class RuleProcessor
}
foreach (var ovrd in (IList<string>?)m.Rule?.Overrides ?? Array.Empty<string>())
{
// Find all overriden rules and mark them for removal from issues list
foreach (var om in resultsList.FindAll(x => x.Rule?.Id == ovrd))
if (om.Boundary.Index >= m.Boundary.Index &&
foreach (var om in resultsList.FindAll(x => x.Rule?.Id == ovrd))
{
if (om.Boundary.Index >= m.Boundary.Index &&
om.Boundary.Index <= m.Boundary.Index + m.Boundary.Length)
{
removes.Add(om);
}
}
}
}
// Remove overriden rules

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

@ -87,17 +87,19 @@ public class RulesVerifier
_logger.LogError(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_DUPLICATEID_FAIL), rule.Key);
var relevantStati = ruleStatuses.Where(x => x.RulesId == rule.Key);
foreach (var status in relevantStati)
{
status.Errors =
status.Errors.Append(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULES_DUPLICATEID_FAIL, rule.Key));
}
}
}
var allTags = ruleSet.GetAppInspectorRules().SelectMany(x => x.Tags ?? Array.Empty<string>()).ToList();
var rulesWithDependsOnWithNoMatchingTags = ruleSet.GetAppInspectorRules().Where(x => !x.DependsOnTags?.All(tag => allTags.Contains(tag)) ?? false);
foreach(var dependslessRule in rulesWithDependsOnWithNoMatchingTags)
foreach (var dependslessRule in rulesWithDependsOnWithNoMatchingTags)
{
_logger.LogError(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_DEPENDS_ON_TAG_MISSING), dependslessRule.Id);
foreach(var status in ruleStatuses.Where(x => x.RulesId == dependslessRule.Id))
foreach (var status in ruleStatuses.Where(x => x.RulesId == dependslessRule.Id))
{
status.Errors = status.Errors.Append(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULES_DEPENDS_ON_TAG_MISSING, dependslessRule.Id));
}
@ -122,19 +124,20 @@ public class RulesVerifier
if (rule.AppliesTo != null)
{
var languages = _options.LanguageSpecs.GetNames();
// Check for unknown language
foreach (var lang in rule.AppliesTo)
if (!string.IsNullOrEmpty(lang))
{
if (!languages.Any(x => x.Equals(lang, StringComparison.CurrentCultureIgnoreCase)))
{
_logger.LogError(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_LANGUAGE_FAIL), rule.Id ?? "", lang);
errors.Add(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULES_LANGUAGE_FAIL, rule.Id ?? "", lang));
}
}
foreach (string lang in
// Check for unknown language
from lang in rule.AppliesTo
where !string.IsNullOrEmpty(lang)
where !languages.Any(x => x.Equals(lang, StringComparison.CurrentCultureIgnoreCase))
select lang)
{
_logger.LogError(MsgHelp.GetString(MsgHelp.ID.VERIFY_RULES_LANGUAGE_FAIL), rule.Id ?? "", lang);
errors.Add(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULES_LANGUAGE_FAIL, rule.Id ?? "", lang));
}
}
foreach (var pattern in (IList<string>?)rule.FileRegexes ?? Array.Empty<string>())
{
try
{
_ = new Regex(pattern, RegexOptions.Compiled);
@ -146,6 +149,7 @@ public class RulesVerifier
errors.Add(MsgHelp.FormatString(MsgHelp.ID.VERIFY_RULES_REGEX_FAIL, rule.Id ?? "", pattern ?? "",
e.Message));
}
}
//valid search pattern
foreach (var searchPattern in rule.Patterns ?? Array.Empty<SearchPattern>())

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

@ -146,6 +146,7 @@ public class TextContainer
else
{
foreach (var ele in values)
{
// Private access hack
// The idx field is the start of the JSON element, including markup that isn't directly part of the element itself
if (field.GetValue(ele) is int idx)
@ -162,6 +163,7 @@ public class TextContainer
yield return (eleString, location);
}
}
}
}
}
@ -243,7 +245,10 @@ public class TextContainer
suffixLoc = FullContent.Length - 1;
}
for (var i = prefixLoc; i <= suffixLoc; i++) CommentedStates[i] = true;
for (var i = prefixLoc; i <= suffixLoc; i++)
{
CommentedStates[i] = true;
}
}
}
}
@ -320,12 +325,14 @@ public class TextContainer
Boundary result = new();
for (var i = 0; i < LineEnds.Count; i++)
{
if (LineEnds[i] >= index)
{
result.Index = LineStarts[i];
result.Length = LineEnds[i] - LineStarts[i] + 1;
break;
}
}
return result;
}
@ -355,6 +362,7 @@ public class TextContainer
public Location GetLocation(int index)
{
for (var i = 1; i < LineEnds.Count; i++)
{
if (LineEnds[i] >= index)
{
return new Location
@ -363,6 +371,7 @@ public class TextContainer
Line = i
};
}
}
return new Location();
}

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

@ -48,10 +48,12 @@ public class TypedRuleSet<T> : AbstractRuleSet, IEnumerable<T> where T : Rule
private IEnumerable<T> AppInspectorRulesAsEnumerableT()
{
foreach (var rule in _rules)
{
if (rule is T ruleAsT)
{
yield return ruleAsT;
}
}
}
@ -93,7 +95,9 @@ public class TypedRuleSet<T> : AbstractRuleSet, IEnumerable<T> where T : Rule
}
foreach (var filename in Directory.EnumerateFileSystemEntries(path, "*.json", SearchOption.AllDirectories))
{
AddFile(filename, tag);
}
}
/// <summary>
@ -140,7 +144,10 @@ public class TypedRuleSet<T> : AbstractRuleSet, IEnumerable<T> where T : Rule
/// <param name="collection"> Collection of rules </param>
public void AddRange(IEnumerable<T>? collection)
{
foreach (var rule in collection ?? Array.Empty<T>()) AddRule(rule);
foreach (var rule in collection ?? Array.Empty<T>())
{
AddRule(rule);
}
}
/// <summary>

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

@ -537,7 +537,10 @@ windows
private void DeleteTestFiles(IEnumerable<string> pathsToDelete)
{
foreach (var path in pathsToDelete) File.Delete(path);
foreach (var path in pathsToDelete)
{
File.Delete(path);
}
}
/// <summary>

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

@ -42,9 +42,15 @@ public class TestDefaultRules
foreach (var unverified in result.Unverified)
{
logger.Log(LogLevel.Error, "Failed to validate {0}", unverified.RulesId);
foreach (var error in unverified.Errors) logger.Log(LogLevel.Error, error);
foreach (var error in unverified.Errors)
{
logger.Log(LogLevel.Error, error);
}
foreach (var oatError in unverified.OatIssues) logger.Log(LogLevel.Error, oatError.Description);
foreach (var oatError in unverified.OatIssues)
{
logger.Log(LogLevel.Error, oatError.Description);
}
}
logger.Log(LogLevel.Information, "{0} of {1} rules have positive self tests.",
@ -53,9 +59,14 @@ public class TestDefaultRules
result.RuleStatusList.Count(x => x.HasNegativeSelfTests), result.RuleStatusList.Count);
foreach (var rule in result.RuleStatusList.Where(x => !x.HasPositiveSelfTests))
{
logger.Log(LogLevel.Warning, "Rule {0} does not have any positive test cases", rule.RulesId);
}
foreach (var rule in result.RuleStatusList.Where(x => !x.HasNegativeSelfTests))
{
logger.Log(LogLevel.Warning, "Rule {0} does not have any negative test cases", rule.RulesId);
}
Assert.AreEqual(VerifyRulesResult.ExitCode.Verified, result.ResultCode);
Assert.AreNotEqual(0, result.RuleStatusList.Count);

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

@ -451,7 +451,11 @@ int main(int argc, char **argv)
RulesVerifier verifier = new(new RulesVerifierOptions { LoggerFactory = _loggerFactory });
var oatIssues = verifier.CheckIntegrity(rules).SelectMany(x => x.OatIssues);
foreach (var violation in oatIssues) _logger.LogDebug(violation.Description);
foreach (var violation in oatIssues)
{
_logger.LogDebug(violation.Description);
}
Assert.AreEqual(expectedNumIssues, verifier.CheckIntegrity(rules).Sum(x => x.OatIssues.Count()));
}

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

@ -96,10 +96,12 @@ public static class TestHelpers
int i;
for (i = 0; i < contentLines.Length; i++)
{
if (contentLines[i].Contains("[UniqueTags]"))
{
break;
}
}
i++; //get past marker
while (!contentLines[i].Contains("Select Counters"))

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

@ -171,8 +171,15 @@ public class AnalyzeCommand
//create metadata helper to wrap and help populate metadata from scan
_metaDataHelper = new MetaDataHelper(string.Join(',', _options.SourcePath));
DateScanned = DateTime.Now;
foreach (var confidence in _options.ConfidenceFilters) _confidence |= confidence;
foreach (var severity in _options.SeverityFilters) _severity |= severity;
foreach (var confidence in _options.ConfidenceFilters)
{
_confidence |= confidence;
}
foreach (var severity in _options.SeverityFilters)
{
_severity |= severity;
}
_logger.LogTrace("AnalyzeCommand::ConfigSourcetoScan");
@ -182,6 +189,7 @@ public class AnalyzeCommand
}
foreach (var entry in _options.SourcePath)
{
if (Directory.Exists(entry))
{
_srcfileList.AddRange(Directory.EnumerateFiles(entry, "*.*", SearchOption.AllDirectories));
@ -194,6 +202,7 @@ public class AnalyzeCommand
{
throw new OpException(MsgHelp.FormatString(MsgHelp.ID.CMD_INVALID_FILE_OR_DIR, entry));
}
}
if (_srcfileList.Count == 0)
{
@ -233,7 +242,9 @@ public class AnalyzeCommand
{
foreach (var filename in Directory.EnumerateFileSystemEntries(_options.CustomRulesPath, "*.json",
SearchOption.AllDirectories))
{
VerifyFile(filename);
}
}
else if (File.Exists(_options.CustomRulesPath))
{
@ -632,6 +643,7 @@ public class AnalyzeCommand
Extractor extractor = new();
// For every file, if the file isn't excluded return it, and if it is track the exclusion in the metadata
foreach (var srcFile in _srcfileList)
{
if (_fileExclusionList.Any(x => x.IsMatch(srcFile)))
{
_metaDataHelper?.Metadata.Files.Add(new FileRecord { FileName = srcFile, Status = ScanState.Skipped });
@ -667,13 +679,17 @@ public class AnalyzeCommand
// This works if the contents contain any kind of file.
// If the file is an archive this gets all the entries it contains.
// If the file is not an archive, the stream is wrapped in a FileEntry container and yielded
foreach (var entry in extractor.Extract(srcFile, contents, opts)) yield return entry;
foreach (var entry in extractor.Extract(srcFile, contents, opts))
{
yield return entry;
}
}
}
// Be sure to close the stream after we are done processing it.
contents?.Dispose();
}
}
}
/// <summary>
@ -686,6 +702,7 @@ public class AnalyzeCommand
Extractor extractor = new();
foreach (var srcFile in _srcfileList)
{
if (_fileExclusionList.Any(x => x.IsMatch(srcFile)))
{
_metaDataHelper?.Metadata.Files.Add(new FileRecord { FileName = srcFile, Status = ScanState.Skipped });
@ -698,8 +715,11 @@ public class AnalyzeCommand
Parallel = false, DenyFilters = _options.FilePathExclusions,
MemoryStreamCutoff = 1
}))
{
yield return entry;
}
}
}
}
@ -862,7 +882,10 @@ public class AnalyzeCommand
{
try
{
foreach (var entry in EnumerateFileEntries()) fileQueue.Add(entry);
foreach (var entry in EnumerateFileEntries())
{
fileQueue.Add(entry);
}
}
catch (OverflowException e)
{
@ -1020,11 +1043,13 @@ public class AnalyzeCommand
cts.Cancel();
// Populate skips for all the entries we didn't process
foreach (var entry in fileEntries.Where(x => _metaDataHelper.Files.All(y => x.FullPath != y.FileName)))
{
_metaDataHelper.Files.Add(new FileRecord
{
AccessTime = entry.AccessTime, CreateTime = entry.CreateTime, ModifyTime = entry.ModifyTime,
FileName = entry.FullPath, Status = ScanState.TimeOutSkipped
});
}
}
}
else

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

@ -114,8 +114,12 @@ public class ExportTagsCommand
HashSet<string> tags = new();
foreach (var rule in _rules.GetAppInspectorRules())
foreach (var tag in (IList<string>?)rule.Tags ?? Array.Empty<string>())
tags.Add(tag);
{
foreach (var tag in (IList<string>?)rule.Tags ?? Array.Empty<string>())
{
tags.Add(tag);
}
}
exportTagsResult.TagsList = tags.ToList();
exportTagsResult.TagsList.Sort();

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

@ -224,18 +224,22 @@ public class TagDiffCommand
var added = list2.Except(list1);
foreach (var add in added)
{
tagDiffResult.TagDiffList.Add(new TagDiff
{
Source = TagDiff.DiffSource.Source2,
Tag = add
});
}
foreach (var remove in removed)
{
tagDiffResult.TagDiffList.Add(new TagDiff
{
Source = TagDiff.DiffSource.Source1,
Tag = remove
});
}
if (tagDiffResult.TagDiffList.Count > 0)
{

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

@ -66,6 +66,7 @@ public class MetaDataHelper
{
//special handling for standard characteristics in report
foreach (string tag in matchRecord.Tags ?? Array.Empty<string>())
{
switch (tag)
{
case "Metadata.Application.Author":
@ -108,6 +109,7 @@ public class MetaDataHelper
break;
}
}
//Special handling; attempt to detect app types...review for multiple pattern rule limitation
string solutionType = DetectSolutionType(matchRecord);
@ -190,7 +192,10 @@ public class MetaDataHelper
Metadata.Languages = new SortedDictionary<string, int>(Languages);
foreach (MetricTagCounter metricTagCounter in TagCounters.Values) Metadata.TagCounters?.Add(metricTagCounter);
foreach (MetricTagCounter metricTagCounter in TagCounters.Values)
{
Metadata.TagCounters?.Add(metricTagCounter);
}
}
/// <summary>