diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 000000000..1b50c1aa6
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,678 @@
+# Version: 4.1.1 (Using https://semver.org/)
+# Updated: 2022-05-23
+# See https://github.com/RehanSaeed/EditorConfig/releases for release notes.
+# See https://github.com/RehanSaeed/EditorConfig for updates to this file.
+# See http://EditorConfig.org for more information about .editorconfig files.
+
+##########################################
+# Common Settings
+##########################################
+
+# This file is the top-most EditorConfig file
+root = true
+
+# All Files
+[*]
+charset = utf-8
+indent_style = space
+indent_size = 4
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+##########################################
+# File Extension Settings
+##########################################
+
+# Visual Studio Solution Files
+[*.sln]
+indent_style = tab
+
+# Visual Studio XML Project Files
+[*.{csproj,vbproj,vcxproj.filters,proj,projitems,shproj}]
+indent_size = 2
+
+# XML Configuration Files
+[*.{xml,config,props,targets,nuspec,resx,ruleset,vsixmanifest,vsct}]
+indent_size = 2
+
+# JSON Files
+[*.{json,json5,webmanifest}]
+indent_size = 2
+
+# YAML Files
+[*.{yml,yaml}]
+indent_size = 2
+
+# Markdown Files
+[*.{md,mdx}]
+trim_trailing_whitespace = false
+
+# Web Files
+[*.{htm,html,js,jsm,ts,tsx,cjs,cts,ctsx,mjs,mts,mtsx,css,sass,scss,less,pcss,svg,vue}]
+indent_size = 2
+
+# Batch Files
+[*.{cmd,bat}]
+end_of_line = crlf
+
+# Bash Files
+[*.sh]
+end_of_line = lf
+
+# Makefiles
+[Makefile]
+indent_style = tab
+
+##########################################
+# Default .NET Code Style Severities
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/configuration-options#scope
+##########################################
+
+[*.{cs,csx,cake,vb,vbx}]
+# Default Severity for all .NET Code Style rules below
+dotnet_analyzer_diagnostic.severity = warning
+
+##########################################
+# Language Rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules
+##########################################
+
+# .NET Style Rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#net-style-rules
+[*.{cs,csx,cake,vb,vbx}]
+# "this." and "Me." qualifiers
+dotnet_style_qualification_for_field = true:warning
+dotnet_style_qualification_for_property = true:warning
+dotnet_style_qualification_for_method = true:warning
+dotnet_style_qualification_for_event = true:warning
+# Language keywords instead of framework type names for type references
+dotnet_style_predefined_type_for_locals_parameters_members = true:warning
+dotnet_style_predefined_type_for_member_access = true:warning
+# Modifier preferences
+dotnet_style_require_accessibility_modifiers = always:warning
+csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:warning
+visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:warning
+dotnet_style_readonly_field = true:warning
+# Parentheses preferences
+dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning
+dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning
+dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning
+dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning
+# Expression-level preferences
+dotnet_style_object_initializer = true:warning
+dotnet_style_collection_initializer = true:warning
+dotnet_style_explicit_tuple_names = true:warning
+dotnet_style_prefer_inferred_tuple_names = true:warning
+dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning
+dotnet_style_prefer_auto_properties = true:warning
+dotnet_style_prefer_conditional_expression_over_assignment = false:suggestion
+dotnet_diagnostic.IDE0045.severity = suggestion
+dotnet_style_prefer_conditional_expression_over_return = false:suggestion
+dotnet_diagnostic.IDE0046.severity = suggestion
+dotnet_style_prefer_compound_assignment = true:warning
+dotnet_style_prefer_simplified_interpolation = true:warning
+dotnet_style_prefer_simplified_boolean_expressions = true:warning
+# Null-checking preferences
+dotnet_style_coalesce_expression = true:warning
+dotnet_style_null_propagation = true:warning
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning
+# File header preferences
+# file_header_template = \n© PROJECT-AUTHOR\n
+# If you use StyleCop, you'll need to disable SA1636: File header copyright text should match.
+# dotnet_diagnostic.SA1636.severity = none
+# Undocumented
+dotnet_style_operator_placement_when_wrapping = end_of_line:warning
+csharp_style_prefer_null_check_over_type_check = true:warning
+
+# C# Style Rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#c-style-rules
+[*.{cs,csx,cake}]
+# 'var' preferences
+csharp_style_var_for_built_in_types = true:warning
+csharp_style_var_when_type_is_apparent = true:warning
+csharp_style_var_elsewhere = true:warning
+# Expression-bodied members
+csharp_style_expression_bodied_methods = true:warning
+csharp_style_expression_bodied_constructors = true:warning
+csharp_style_expression_bodied_operators = true:warning
+csharp_style_expression_bodied_properties = true:warning
+csharp_style_expression_bodied_indexers = true:warning
+csharp_style_expression_bodied_accessors = true:warning
+csharp_style_expression_bodied_lambdas = true:warning
+csharp_style_expression_bodied_local_functions = true:warning
+# Pattern matching preferences
+csharp_style_pattern_matching_over_is_with_cast_check = true:warning
+csharp_style_pattern_matching_over_as_with_null_check = true:warning
+csharp_style_prefer_switch_expression = true:warning
+csharp_style_prefer_pattern_matching = true:warning
+csharp_style_prefer_not_pattern = true:warning
+# Expression-level preferences
+csharp_style_inlined_variable_declaration = true:warning
+csharp_prefer_simple_default_expression = true:warning
+csharp_style_pattern_local_over_anonymous_function = true:warning
+csharp_style_deconstructed_variable_declaration = true:warning
+csharp_style_prefer_index_operator = true:warning
+csharp_style_prefer_range_operator = true:warning
+csharp_style_implicit_object_creation_when_type_is_apparent = true:warning
+# "Null" checking preferences
+csharp_style_throw_expression = true:warning
+csharp_style_conditional_delegate_call = true:warning
+# Code block preferences
+csharp_prefer_braces = true:warning
+csharp_prefer_simple_using_statement = true:suggestion
+dotnet_diagnostic.IDE0063.severity = suggestion
+# 'using' directive preferences
+csharp_using_directive_placement = inside_namespace:warning
+# Modifier preferences
+csharp_prefer_static_local_function = true:warning
+
+##########################################
+# Unnecessary Code Rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/unnecessary-code-rules
+##########################################
+
+# .NET Unnecessary code rules
+[*.{cs,csx,cake,vb,vbx}]
+dotnet_code_quality_unused_parameters = all:warning
+dotnet_remove_unnecessary_suppression_exclusions = none:warning
+
+# C# Unnecessary code rules
+[*.{cs,csx,cake}]
+csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion
+dotnet_diagnostic.IDE0058.severity = suggestion
+csharp_style_unused_value_assignment_preference = discard_variable:suggestion
+dotnet_diagnostic.IDE0059.severity = suggestion
+
+##########################################
+# Formatting Rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules
+##########################################
+
+# .NET formatting rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#net-formatting-rules
+[*.{cs,csx,cake,vb,vbx}]
+# Organize using directives
+dotnet_sort_system_directives_first = true
+dotnet_separate_import_directive_groups = false
+# Dotnet namespace options
+dotnet_style_namespace_match_folder = true:suggestion
+dotnet_diagnostic.IDE0130.severity = suggestion
+
+# C# formatting rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#c-formatting-rules
+[*.{cs,csx,cake}]
+# Newline options
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#new-line-options
+csharp_new_line_before_open_brace = all
+csharp_new_line_before_else = true
+csharp_new_line_before_catch = true
+csharp_new_line_before_finally = true
+csharp_new_line_before_members_in_object_initializers = true
+csharp_new_line_before_members_in_anonymous_types = true
+csharp_new_line_between_query_expression_clauses = true
+# Indentation options
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#indentation-options
+csharp_indent_case_contents = true
+csharp_indent_switch_labels = true
+csharp_indent_labels = no_change
+csharp_indent_block_contents = true
+csharp_indent_braces = false
+csharp_indent_case_contents_when_block = false
+# Spacing options
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#spacing-options
+csharp_space_after_cast = false
+csharp_space_after_keywords_in_control_flow_statements = true
+csharp_space_between_parentheses = false
+csharp_space_before_colon_in_inheritance_clause = true
+csharp_space_after_colon_in_inheritance_clause = true
+csharp_space_around_binary_operators = before_and_after
+csharp_space_between_method_declaration_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_call_parameter_list_parentheses = false
+csharp_space_between_method_call_empty_parameter_list_parentheses = false
+csharp_space_between_method_call_name_and_opening_parenthesis = false
+csharp_space_after_comma = true
+csharp_space_before_comma = false
+csharp_space_after_dot = false
+csharp_space_before_dot = false
+csharp_space_after_semicolon_in_for_statement = true
+csharp_space_before_semicolon_in_for_statement = false
+csharp_space_around_declaration_statements = false
+csharp_space_before_open_square_brackets = false
+csharp_space_between_empty_square_brackets = false
+csharp_space_between_square_brackets = false
+# Wrap options
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#wrap-options
+csharp_preserve_single_line_statements = false
+csharp_preserve_single_line_blocks = true
+# Namespace options
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#namespace-options
+csharp_style_namespace_declarations = file_scoped:warning
+
+##########################################
+# .NET Naming Rules
+# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/naming-rules
+##########################################
+
+[*.{cs,csx,cake,vb,vbx}]
+
+##########################################
+# Styles
+##########################################
+
+# camel_case_style - Define the camelCase style
+dotnet_naming_style.camel_case_style.capitalization = camel_case
+# pascal_case_style - Define the PascalCase style
+dotnet_naming_style.pascal_case_style.capitalization = pascal_case
+# first_upper_style - The first character must start with an upper-case character
+dotnet_naming_style.first_upper_style.capitalization = first_word_upper
+# prefix_interface_with_i_style - Interfaces must be PascalCase and the first character of an interface must be an 'I'
+dotnet_naming_style.prefix_interface_with_i_style.capitalization = pascal_case
+dotnet_naming_style.prefix_interface_with_i_style.required_prefix = I
+# prefix_type_parameters_with_t_style - Generic Type Parameters must be PascalCase and the first character must be a 'T'
+dotnet_naming_style.prefix_type_parameters_with_t_style.capitalization = pascal_case
+dotnet_naming_style.prefix_type_parameters_with_t_style.required_prefix = T
+# disallowed_style - Anything that has this style applied is marked as disallowed
+dotnet_naming_style.disallowed_style.capitalization = pascal_case
+dotnet_naming_style.disallowed_style.required_prefix = ____RULE_VIOLATION____
+dotnet_naming_style.disallowed_style.required_suffix = ____RULE_VIOLATION____
+# internal_error_style - This style should never occur... if it does, it indicates a bug in file or in the parser using the file
+dotnet_naming_style.internal_error_style.capitalization = pascal_case
+dotnet_naming_style.internal_error_style.required_prefix = ____INTERNAL_ERROR____
+dotnet_naming_style.internal_error_style.required_suffix = ____INTERNAL_ERROR____
+
+##########################################
+# .NET Design Guideline Field Naming Rules
+# Naming rules for fields follow the .NET Framework design guidelines
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/index
+##########################################
+
+# All public/protected/protected_internal constant fields must be PascalCase
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/field
+dotnet_naming_symbols.public_protected_constant_fields_group.applicable_accessibilities = public, protected, protected_internal
+dotnet_naming_symbols.public_protected_constant_fields_group.required_modifiers = const
+dotnet_naming_symbols.public_protected_constant_fields_group.applicable_kinds = field
+dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.symbols = public_protected_constant_fields_group
+dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.style = pascal_case_style
+dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.severity = warning
+
+# All public/protected/protected_internal static readonly fields must be PascalCase
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/field
+dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_accessibilities = public, protected, protected_internal
+dotnet_naming_symbols.public_protected_static_readonly_fields_group.required_modifiers = static, readonly
+dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_kinds = field
+dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.symbols = public_protected_static_readonly_fields_group
+dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style
+dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.severity = warning
+
+# No other public/protected/protected_internal fields are allowed
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/field
+dotnet_naming_symbols.other_public_protected_fields_group.applicable_accessibilities = public, protected, protected_internal
+dotnet_naming_symbols.other_public_protected_fields_group.applicable_kinds = field
+dotnet_naming_rule.other_public_protected_fields_disallowed_rule.symbols = other_public_protected_fields_group
+dotnet_naming_rule.other_public_protected_fields_disallowed_rule.style = disallowed_style
+dotnet_naming_rule.other_public_protected_fields_disallowed_rule.severity = error
+
+##########################################
+# StyleCop Field Naming Rules
+# Naming rules for fields follow the StyleCop analyzers
+# This does not override any rules using disallowed_style above
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers
+##########################################
+
+# All constant fields must be PascalCase
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1303.md
+dotnet_naming_symbols.stylecop_constant_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private
+dotnet_naming_symbols.stylecop_constant_fields_group.required_modifiers = const
+dotnet_naming_symbols.stylecop_constant_fields_group.applicable_kinds = field
+dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.symbols = stylecop_constant_fields_group
+dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.style = pascal_case_style
+dotnet_naming_rule.stylecop_constant_fields_must_be_pascal_case_rule.severity = warning
+
+# All static readonly fields must be PascalCase
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1311.md
+dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected, private
+dotnet_naming_symbols.stylecop_static_readonly_fields_group.required_modifiers = static, readonly
+dotnet_naming_symbols.stylecop_static_readonly_fields_group.applicable_kinds = field
+dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.symbols = stylecop_static_readonly_fields_group
+dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style
+dotnet_naming_rule.stylecop_static_readonly_fields_must_be_pascal_case_rule.severity = warning
+
+# No non-private instance fields are allowed
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md
+dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_accessibilities = public, internal, protected_internal, protected, private_protected
+dotnet_naming_symbols.stylecop_fields_must_be_private_group.applicable_kinds = field
+dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.symbols = stylecop_fields_must_be_private_group
+dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.style = disallowed_style
+dotnet_naming_rule.stylecop_instance_fields_must_be_private_rule.severity = error
+
+# Private fields must be camelCase
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1306.md
+dotnet_naming_symbols.stylecop_private_fields_group.applicable_accessibilities = private
+dotnet_naming_symbols.stylecop_private_fields_group.applicable_kinds = field
+dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.symbols = stylecop_private_fields_group
+dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.style = camel_case_style
+dotnet_naming_rule.stylecop_private_fields_must_be_camel_case_rule.severity = warning
+
+# Local variables must be camelCase
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1312.md
+dotnet_naming_symbols.stylecop_local_fields_group.applicable_accessibilities = local
+dotnet_naming_symbols.stylecop_local_fields_group.applicable_kinds = local
+dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.symbols = stylecop_local_fields_group
+dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.style = camel_case_style
+dotnet_naming_rule.stylecop_local_fields_must_be_camel_case_rule.severity = silent
+
+# This rule should never fire. However, it's included for at least two purposes:
+# First, it helps to understand, reason about, and root-case certain types of issues, such as bugs in .editorconfig parsers.
+# Second, it helps to raise immediate awareness if a new field type is added (as occurred recently in C#).
+dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_accessibilities = *
+dotnet_naming_symbols.sanity_check_uncovered_field_case_group.applicable_kinds = field
+dotnet_naming_rule.sanity_check_uncovered_field_case_rule.symbols = sanity_check_uncovered_field_case_group
+dotnet_naming_rule.sanity_check_uncovered_field_case_rule.style = internal_error_style
+dotnet_naming_rule.sanity_check_uncovered_field_case_rule.severity = error
+
+
+##########################################
+# Other Naming Rules
+##########################################
+
+# All of the following must be PascalCase:
+# - Namespaces
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-namespaces
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md
+# - Classes and Enumerations
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1300.md
+# - Delegates
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces#names-of-common-types
+# - Constructors, Properties, Events, Methods
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-type-members
+dotnet_naming_symbols.element_group.applicable_kinds = namespace, class, enum, struct, delegate, event, method, property
+dotnet_naming_rule.element_rule.symbols = element_group
+dotnet_naming_rule.element_rule.style = pascal_case_style
+dotnet_naming_rule.element_rule.severity = warning
+
+# Interfaces use PascalCase and are prefixed with uppercase 'I'
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
+dotnet_naming_symbols.interface_group.applicable_kinds = interface
+dotnet_naming_rule.interface_rule.symbols = interface_group
+dotnet_naming_rule.interface_rule.style = prefix_interface_with_i_style
+dotnet_naming_rule.interface_rule.severity = warning
+
+# Generics Type Parameters use PascalCase and are prefixed with uppercase 'T'
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
+dotnet_naming_symbols.type_parameter_group.applicable_kinds = type_parameter
+dotnet_naming_rule.type_parameter_rule.symbols = type_parameter_group
+dotnet_naming_rule.type_parameter_rule.style = prefix_type_parameters_with_t_style
+dotnet_naming_rule.type_parameter_rule.severity = warning
+
+# Function parameters use camelCase
+# https://docs.microsoft.com/dotnet/standard/design-guidelines/naming-parameters
+dotnet_naming_symbols.parameters_group.applicable_kinds = parameter
+dotnet_naming_rule.parameters_rule.symbols = parameters_group
+dotnet_naming_rule.parameters_rule.style = camel_case_style
+dotnet_naming_rule.parameters_rule.severity = warning
+
+##########################################
+# License
+##########################################
+# The following applies as to the .editorconfig file ONLY, and is
+# included below for reference, per the requirements of the license
+# corresponding to this .editorconfig file.
+# See: https://github.com/RehanSaeed/EditorConfig
+#
+# MIT License
+#
+# Copyright (c) 2017-2019 Muhammad Rehan Saeed
+# Copyright (c) 2019 Henry Gabryjelski
+#
+# Permission is hereby granted, free of charge, to any
+# person obtaining a copy of this software and associated
+# documentation files (the "Software"), to deal in the
+# Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute,
+# sublicense, and/or sell copies of the Software, and to permit
+# persons to whom the Software is furnished to do so, subject
+# to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+# OTHER DEALINGS IN THE SOFTWARE.
+##########################################
+
+##########################################
+# Custom rules
+##########################################
+[*.cs]
+# See https://github.com/microsoft/component-detection/issues/202
+##########################################
+# Provided by StyleCop.Analyzers
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers
+##########################################
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1101.md
+# Prefix local calls with this
+dotnet_diagnostic.SA1101.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1105.md
+# Single line comment should begin with a space
+dotnet_diagnostic.SA1105.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1008.md
+# Opening parenthesis should not be followed by a space.
+dotnet_diagnostic.SA1008.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1009.md
+# Closing parenthesis should not be followed by a space
+dotnet_diagnostic.SA1009.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1011.md
+# Closing square bracket should be followed by a space
+dotnet_diagnostic.SA1011.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1012.md
+# Opening brace should be preceded by a space
+dotnet_diagnostic.SA1012.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1013.md
+# Closing brace should be preceded by a space
+dotnet_diagnostic.SA1013.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1013.md
+# Opening brace should be preceded by a space
+dotnet_diagnostic.SA1013.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1026.md
+# The keyword 'new' should not be followed by a space or a blank line
+dotnet_diagnostic.SA1026.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1108.md
+# Block statements should not contain embedded comments
+dotnet_diagnostic.SA1108.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1114.md
+# Parameter list should follow declaration
+dotnet_diagnostic.SA1114.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1117.md
+# The parameters should all be placed on the same line or each parameter should be placed on its own line
+dotnet_diagnostic.SA1117.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1118.md
+# The parameter spans multiple lines
+dotnet_diagnostic.SA1118.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1135.md
+# Using directive for namespace '...' should be qualified
+dotnet_diagnostic.SA1135.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1137.md
+# Elements should have the same indentation
+dotnet_diagnostic.SA1137.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1142.md
+# Refer to tuple fields by name
+dotnet_diagnostic.SA1142.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1200.md
+# Using directive should appear within a namespace declaration
+dotnet_diagnostic.SA1200.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1201.md
+# A field should not follow a property
+dotnet_diagnostic.SA1201.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1202.md
+# Constant fields should appear before non-constant fields
+dotnet_diagnostic.SA1202.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1203.md
+# 'public' members should come before 'private' members
+dotnet_diagnostic.SA1203.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1204.md
+# Static members should appear before non-static members
+dotnet_diagnostic.SA1204.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1208.md
+# Using directive for '...' should appear before directive for '...'
+dotnet_diagnostic.SA1208.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1210.md
+# Using directives should be ordered alphabetically by the namespaces
+dotnet_diagnostic.SA1210.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1214.md
+# Readonly fields should appear before non-readonly fields
+dotnet_diagnostic.SA1214.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1216.md
+# Using static directives should be placed at the correct location
+dotnet_diagnostic.SA1216.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1316.md
+# Tuple element names should use correct casing
+dotnet_diagnostic.SA1316.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1401.md
+# Field should be private
+dotnet_diagnostic.SA1401.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1413.md
+# Use trailing comma in multi-line initializers
+dotnet_diagnostic.SA1413.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1414.md
+# Tuple types in signatures should have element names
+dotnet_diagnostic.SA1414.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1500.md
+# Braces for multi-line statements should not share line
+dotnet_diagnostic.SA1500.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1515.md
+# Single-line comment should be preceded by blank line
+dotnet_diagnostic.SA1515.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1518.md
+# File is required to end with a single newline character
+dotnet_diagnostic.SA1518.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1600.md
+# Elements should be documented
+dotnet_diagnostic.SA1600.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1602.md
+# Enumeration items should be documented
+dotnet_diagnostic.SA1602.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1604.md
+# Element documentation should have summary
+dotnet_diagnostic.SA1604.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1611.md
+# The documentation for parameter '...' is missing
+dotnet_diagnostic.SA1611.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1614.md
+# Element parameter documentation should have text
+dotnet_diagnostic.SA1614.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1615.md
+# Element return value should be documented
+dotnet_diagnostic.SA1615.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1616.md
+# Element return value documentation should have text
+dotnet_diagnostic.SA1616.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1617.md
+# Void return value should not be documented
+dotnet_diagnostic.SA1617.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1629.md
+# Documentation text should end with a period
+dotnet_diagnostic.SA1629.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1633.md
+# The file header is missing or not located at the top of the file.
+dotnet_diagnostic.SA1633.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1642.md
+# Constructor summary documentation should begin with standard text
+dotnet_diagnostic.SA1642.severity = suggestion
+
+# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1648.md
+# inheritdoc should be used with inheriting class
+dotnet_diagnostic.SA1648.severity = suggestion
+
+##########################################
+# Provided by Microsoft.VisualStudio.Threading.Analyzers
+# https://github.com/Microsoft/vs-threading
+##########################################
+
+# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD002.md
+# Synchronously waiting on tasks or awaiters may cause deadlocks. Use await or JoinableTaskFactory.Run instead.
+dotnet_diagnostic.VSTHRD002.severity = suggestion
+
+# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD103.md
+# Result synchronously blocks. Use await instead.
+dotnet_diagnostic.VSTHRD103.severity = suggestion
+
+# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD101.md
+# Avoid using async lambda for a void returning delegate type, because any exceptions not handled by the delegate will crash the process
+dotnet_diagnostic.VSTHRD101.severity = suggestion
+
+# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD104.md
+# Expose an async version of this method that does not synchronously block. Then simplify this method to call that async method within a JoinableTaskFactory.Run delegate.
+dotnet_diagnostic.VSTHRD104.severity = suggestion
+
+# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD111.md
+# Add .ConfigureAwait(bool) to your await expression
+dotnet_diagnostic.VSTHRD111.severity = suggestion
+
+# https://github.com/microsoft/vs-threading/blob/main/doc/analyzers/VSTHRD200.md
+# Use "Async" suffix in names of methods that return an awaitable type
+dotnet_diagnostic.VSTHRD200.severity = suggestion
+
+##########################################
+# Provided by Roslyn
+# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/
+##########################################
+
+# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0618
+# '...' is obsolete
+dotnet_diagnostic.CS0618.severity = suggestion
+
+# https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1591
+# Missing XML comment for publicly visible type or member '...'
+dotnet_diagnostic.CS1591.severity = suggestion
diff --git a/.tours/add-a-telemetry-record.tour b/.tours/add-a-telemetry-record.tour
deleted file mode 100644
index dca0f2ad5..000000000
--- a/.tours/add-a-telemetry-record.tour
+++ /dev/null
@@ -1,59 +0,0 @@
-{
- "$schema": "https://aka.ms/codetour-schema",
- "title": "Add and using a telemetry record",
- "steps": [
- {
- "directory": "src/Common/Telemetry/Records",
- "description": "Create a new file `MyTelemetryRecord.cs` in `./src/Common/Telemetry/Records/`",
- "title": "Creating the file"
- },
- {
- "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs",
- "selection": {
- "start": {
- "line": 3,
- "character": 5
- },
- "end": {
- "line": 3,
- "character": 11
- }
- },
- "description": "Make sure it's a public class.",
- "title": "Configuring the class"
- },
- {
- "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs",
- "selection": {
- "start": {
- "line": 3,
- "character": 55
- },
- "end": {
- "line": 3,
- "character": 86
- }
- },
- "description": "Derive `BaseDetectionTelemetryRecord`",
- "title": "Inheritance"
- },
- {
- "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs",
- "description": "Every telemetry record must have a unique `RecordName`",
- "line": 5,
- "title": "Record Name"
- },
- {
- "file": "src/Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs",
- "description": "Add any additional properties you wish your record to track",
- "line": 7,
- "title": "Setting the properties"
- },
- {
- "file": "src/Detectors/linux/LinuxScanner.cs",
- "description": "Here is an example of how you would use a telemetry record",
- "line": 30,
- "title": "Using your record"
- }
- ]
-}
\ No newline at end of file
diff --git a/.tours/getting-started.tour b/.tours/getting-started.tour
deleted file mode 100644
index 18170df15..000000000
--- a/.tours/getting-started.tour
+++ /dev/null
@@ -1,53 +0,0 @@
-{
- "$schema": "https://aka.ms/codetour-schema",
- "title": "Getting Started",
- "steps": [
- {
- "title": "Introduction",
- "description": "ComponentDetection is a command line package scanning tool. It produces a graph-based output of all detected components and supports a variety of open source package ecosystems. Let's take a look at how to run it."
- },
- {
- "file": ".vscode/launch.json",
- "description": "These are some the basic arguments necessary for the tool to run. The most important of which are:\n\n* `scan` - the action we want to take\n* `SourceDirectory` - the root directory where we want the recursive scan to start\n\nFor a full breakdown of the arguments available check out [./docs/detector-arguments.md](./docs/detector-arguments.md)\n\nYou can run ComponentDetection with these default arguments using the shortcut `Ctrl`+`Shift`+`B`\n\n[Build](command:workbench.action.tasks.build)",
- "line": 15,
- "title": "Command Line Arguments"
- },
- {
- "title": "Concepts",
- "description": "At a high level:\n\n* `ComponentDetection` starts from a `SourceDirectory` and iterates recursively through the files and directories\n* A `Detector` can specify a list of patterns which it's interested in\n* If a file name matches a pattern, the file contents are read and sent to the `Detector`\n* A `Detector` is responsible for producing a graph of `Components` as the output from processing a file\n* Once all files have been read and processed, `ComponentDetection` accumulates all of the graphs into a final output manifest"
- },
- {
- "directory": "src/Detectors",
- "description": "There are many detectors, at least 1 for each package ecosystem. Let's take a look at a simple example.",
- "title": "Detectors Folder"
- },
- {
- "file": "src/Detectors/cocoapods/PodComponentDetector.cs",
- "description": "Here is an example of a `Detector` for cocoapods components",
- "line": 15,
- "title": "Detector Class"
- },
- {
- "file": "src/Detectors/cocoapods/PodComponentDetector.cs",
- "description": "These are the file patterns which the `Detector` is interested in",
- "line": 21,
- "title": "Search Patterns"
- },
- {
- "file": "src/Detectors/cocoapods/PodComponentDetector.cs",
- "description": "Here is where we register a detected `PodComponent` in the output graph for this file.",
- "line": 330,
- "title": "Registering Components"
- },
- {
- "directory": "src/Contracts/TypedComponent",
- "description": "There are many component types, one for each package ecosystem. That allows us to keep only the information relavant for each ecosystem.",
- "title": "TypedComponents Folder"
- },
- {
- "title": "Wrap Up",
- "description": "Run ComponentDetection (remember: `Ctrl`+`Shift`+`B`) and take a look at the final output in `./scan-output/bcde-output.json`."
- }
- ],
- "isPrimary": true
-}
\ No newline at end of file
diff --git a/Directory.Build.props b/Directory.Build.props
index 352dc82de..1681b2d4b 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,40 +1,32 @@
-
- netcoreapp3.1
- latest
- true
- true
-
+
+ netcoreapp3.1
+ latest
+ true
+ true
+ latest
+ AllEnabledByDefault
+ true
+ true
+
-
- Microsoft
- Microsoft
- Copyright © Microsoft Corporation. All rights reserved.
- true
- MIT
- https://github.com/microsoft/component-detection
- https://github.com/microsoft/component-detection.git
- git
- https://github.com/microsoft/component-detection/releases
-
+
+ Microsoft
+ Microsoft
+ Copyright © Microsoft Corporation. All rights reserved.
+ true
+ MIT
+ https://github.com/microsoft/component-detection
+ https://github.com/microsoft/component-detection.git
+ git
+ https://github.com/microsoft/component-detection/releases
+
-
-
-
-
-
+
+
+
+
+
-
- $(MSBuildThisFileDirectory)analyzers.ruleset
- true
- NU1608,NU5119
-
-
- true
-
-
-
-
-
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 77f5c7b4e..290927d33 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -9,17 +9,17 @@
-
-
+
+
-
-
-
+
+
-
-
-
+
+
+
+
@@ -29,8 +29,8 @@
-
-
+
+
diff --git a/analyzers.ruleset b/analyzers.ruleset
deleted file mode 100644
index 5d9637319..000000000
--- a/analyzers.ruleset
+++ /dev/null
@@ -1,503 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/docs/update-syft.md b/docs/update-syft.md
new file mode 100644
index 000000000..8e96ca932
--- /dev/null
+++ b/docs/update-syft.md
@@ -0,0 +1,51 @@
+# Updating Syft
+
+For container detection we use [Syft][1].
+Occasionally, as new versions of Syft are released, we need to update the version we use.
+To do this:
+
+1. Ensure you're authenticated to Azure and our Azure Container Registry
+
+ ```
+ az login
+ az acr login --name governancecontainerregistry
+ ```
+
+2. Find the [latest version of Syft][2]
+3. Pull the latest container image
+
+ ```
+ $ docker pull docker.io/anchore/syft:v{LATEST}
+ v0.53.4: Pulling from anchore/syft
+ 0d60d5ab2113: Pull complete
+ 26136f3e3dd3: Pull complete
+ 497aa7f04842: Pull complete
+ Digest: sha256:37e85e8efdeaabb1b6f65c5bc175b664cb05d1aaddd0d922130b8e25d6e49726
+ Status: Downloaded newer image for anchore/syft:v{LATEST}
+ docker.io/anchore/syft:v{LATEST}
+ ```
+
+4. Retag the container image
+
+ ```
+ $ docker tag docker.io/anchore/syft:v{LATEST} governancecontainerregistry.azurecr.io/syft:v{LATEST}
+ ```
+
+5. Push the new image to the registry
+
+ ```
+ $ docker push governancecontainerregistry.azurecr.io/syft:v{LATEST}
+ The push refers to repository [governancecontainerregistry.azurecr.io/syft]
+ 9c858c120b14: Pushed
+ 840f3b941d62: Pushed
+ 21ce82bb7448: Pushed
+ v{LATEST: digest: sha256:04ed9c717a814fdccf52758b67333632a0ff16840fc393f5fba5864285eaebbe size: 945
+ ```
+
+6. Update the container reference in [`LinuxScanner`][3]
+7. Update [the models][4] that map the Syft output
+
+[1]: https://github.com/anchore/syft
+[2]: https://github.com/anchore/syft/releases/latest
+[3]: https://github.com/microsoft/component-detection/blob/aaf865e38112fb2448f5866ab06d5898358403f6/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs#L20
+[4]: https://github.com/microsoft/component-detection/blob/main/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs
diff --git a/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs b/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs
index f72b85da5..3284f19f2 100644
--- a/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs
+++ b/src/Microsoft.ComponentDetection.Common/AsyncExecution.cs
@@ -13,9 +13,9 @@ public static async Task ExecuteWithTimeoutAsync(Func> toExecute,
throw new ArgumentNullException(nameof(toExecute));
}
- Task work = Task.Run(toExecute);
+ var work = Task.Run(toExecute);
- bool completedInTime = await Task.Run(() => work.Wait(timeout));
+ var completedInTime = await Task.Run(() => work.Wait(timeout));
if (!completedInTime)
{
throw new TimeoutException($"The execution did not complete in the alotted time ({timeout.TotalSeconds} seconds) and has been terminated prior to completion");
@@ -31,8 +31,8 @@ public static async Task ExecuteVoidWithTimeoutAsync(Action toExecute, TimeSpan
throw new ArgumentNullException(nameof(toExecute));
}
- Task work = Task.Run(toExecute);
- bool completedInTime = await Task.Run(() => work.Wait(timeout));
+ var work = Task.Run(toExecute);
+ var completedInTime = await Task.Run(() => work.Wait(timeout));
if (!completedInTime)
{
throw new TimeoutException($"The execution did not complete in the alotted time ({timeout.TotalSeconds} seconds) and has been terminated prior to completion");
diff --git a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs
index 59646e790..b937f3aa5 100644
--- a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs
+++ b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs
@@ -22,7 +22,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable
additionalCandidateCommands = additionalCandidateCommands ?? Enumerable.Empty();
parameters = parameters ?? new string[0];
var allCommands = new[] { command }.Concat(additionalCandidateCommands);
- if (!commandLocatableCache.TryGetValue(command, out string validCommand))
+ if (!this.commandLocatableCache.TryGetValue(command, out var validCommand))
{
foreach (var commandToTry in allCommands)
{
@@ -36,7 +36,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable
if (result.ExitCode == 0)
{
- commandLocatableCache[command] = validCommand = commandToTry;
+ this.commandLocatableCache[command] = validCommand = commandToTry;
break;
}
}
@@ -53,7 +53,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable
public async Task ExecuteCommand(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
{
- var isCommandLocatable = await CanCommandBeLocated(command, additionalCandidateCommands);
+ var isCommandLocatable = await this.CanCommandBeLocated(command, additionalCandidateCommands);
if (!isCommandLocatable)
{
throw new InvalidOperationException(
@@ -68,7 +68,7 @@ public async Task ExecuteCommand(string command, IEn
using var record = new CommandLineInvocationTelemetryRecord();
- var pathToRun = commandLocatableCache[command];
+ var pathToRun = this.commandLocatableCache[command];
var joinedParameters = string.Join(" ", parameters);
try
{
@@ -119,8 +119,8 @@ private static Task RunProcessAsync(string fileName,
process.StartInfo.WorkingDirectory = workingDirectory.FullName;
}
- string errorText = string.Empty;
- string stdOutText = string.Empty;
+ var errorText = string.Empty;
+ var stdOutText = string.Empty;
var t1 = new Task(() =>
{
@@ -147,12 +147,12 @@ private static Task RunProcessAsync(string fileName,
public async Task CanCommandBeLocated(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters)
{
- return await CanCommandBeLocated(command, additionalCandidateCommands, workingDirectory: null, parameters);
+ return await this.CanCommandBeLocated(command, additionalCandidateCommands, workingDirectory: null, parameters);
}
public async Task ExecuteCommand(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters)
{
- return await ExecuteCommand(command, additionalCandidateCommands, workingDirectory: null, parameters);
+ return await this.ExecuteCommand(command, additionalCandidateCommands, workingDirectory: null, parameters);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs
index d2009f071..82818660b 100644
--- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs
+++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs
@@ -14,21 +14,21 @@ public class ComponentStreamEnumerable : IEnumerable
public ComponentStreamEnumerable(IEnumerable fileEnumerable, ILogger logger)
{
- ToEnumerate = fileEnumerable;
- Logger = logger;
+ this.ToEnumerate = fileEnumerable;
+ this.Logger = logger;
}
public IEnumerator GetEnumerator()
{
- foreach (var filePairing in ToEnumerate)
+ foreach (var filePairing in this.ToEnumerate)
{
if (!filePairing.File.Exists)
{
- Logger.LogWarning($"File {filePairing.File.FullName} does not exist on disk.");
+ this.Logger.LogWarning($"File {filePairing.File.FullName} does not exist on disk.");
yield break;
}
- using var stream = SafeOpenFile(filePairing.File);
+ using var stream = this.SafeOpenFile(filePairing.File);
if (stream == null)
{
@@ -41,7 +41,7 @@ public IEnumerator GetEnumerator()
IEnumerator IEnumerable.GetEnumerator()
{
- return GetEnumerator();
+ return this.GetEnumerator();
}
private Stream SafeOpenFile(FileInfo file)
@@ -52,13 +52,13 @@ private Stream SafeOpenFile(FileInfo file)
}
catch (UnauthorizedAccessException)
{
- Logger.LogWarning($"Unauthorized access exception caught when trying to open {file.FullName}");
+ this.Logger.LogWarning($"Unauthorized access exception caught when trying to open {file.FullName}");
return null;
}
catch (Exception e)
{
- Logger.LogWarning($"Unhandled exception caught when trying to open {file.FullName}");
- Logger.LogException(e, isError: false);
+ this.Logger.LogWarning($"Unhandled exception caught when trying to open {file.FullName}");
+ this.Logger.LogException(e, isError: false);
return null;
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs
index 9f415a0e5..f97bcfefb 100644
--- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs
+++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs
@@ -18,14 +18,14 @@ public class ComponentStreamEnumerableFactory : IComponentStreamEnumerableFactor
public IEnumerable GetComponentStreams(DirectoryInfo directory, IEnumerable searchPatterns, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true)
{
- SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, searchPatterns, Logger, PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories);
- return new ComponentStreamEnumerable(enumerable, Logger);
+ var enumerable = new SafeFileEnumerable(directory, searchPatterns, this.Logger, this.PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories);
+ return new ComponentStreamEnumerable(enumerable, this.Logger);
}
public IEnumerable GetComponentStreams(DirectoryInfo directory, Func fileMatchingPredicate, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true)
{
- SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, fileMatchingPredicate, Logger, PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories);
- return new ComponentStreamEnumerable(enumerable, Logger);
+ var enumerable = new SafeFileEnumerable(directory, fileMatchingPredicate, this.Logger, this.PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories);
+ return new ComponentStreamEnumerable(enumerable, this.Logger);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs
index 3813aa4fd..5346f9487 100644
--- a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs
+++ b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs
@@ -28,18 +28,18 @@ public ComponentRecorder(ILogger log = null, bool enableManualTrackingOfExplicit
public TypedComponent GetComponent(string componentId)
{
- return singleFileRecorders.Select(x => x.GetComponent(componentId)?.Component).Where(x => x != null).FirstOrDefault();
+ return this.singleFileRecorders.Select(x => x.GetComponent(componentId)?.Component).Where(x => x != null).FirstOrDefault();
}
public IEnumerable GetDetectedComponents()
{
IEnumerable detectedComponents;
- if (singleFileRecorders == null)
+ if (this.singleFileRecorders == null)
{
return Enumerable.Empty();
}
- detectedComponents = singleFileRecorders
+ detectedComponents = this.singleFileRecorders
.Select(singleFileRecorder => singleFileRecorder.GetDetectedComponents().Values)
.SelectMany(x => x)
.GroupBy(x => x.Component.Id)
@@ -69,11 +69,11 @@ public ISingleFileComponentRecorder CreateSingleFileComponentRecorder(string loc
throw new ArgumentNullException(nameof(location));
}
- var matching = singleFileRecorders.FirstOrDefault(x => x.ManifestFileLocation == location);
+ var matching = this.singleFileRecorders.FirstOrDefault(x => x.ManifestFileLocation == location);
if (matching == null)
{
- matching = new SingleFileComponentRecorder(location, this, enableManualTrackingOfExplicitReferences, log);
- singleFileRecorders.Add(matching);
+ matching = new SingleFileComponentRecorder(location, this, this.enableManualTrackingOfExplicitReferences, this.log);
+ this.singleFileRecorders.Add(matching);
}
return matching;
@@ -81,12 +81,12 @@ public ISingleFileComponentRecorder CreateSingleFileComponentRecorder(string loc
internal DependencyGraph GetDependencyGraphForLocation(string location)
{
- return singleFileRecorders.Single(x => x.ManifestFileLocation == location).DependencyGraph;
+ return this.singleFileRecorders.Single(x => x.ManifestFileLocation == location).DependencyGraph;
}
public IReadOnlyDictionary GetDependencyGraphsByLocation()
{
- return singleFileRecorders.Where(x => x.DependencyGraph.HasComponents())
+ return this.singleFileRecorders.Where(x => x.DependencyGraph.HasComponents())
.ToImmutableDictionary(x => x.ManifestFileLocation, x => x.DependencyGraph as IDependencyGraph);
}
@@ -98,7 +98,7 @@ public class SingleFileComponentRecorder : ISingleFileComponentRecorder
internal DependencyGraph DependencyGraph { get; }
- IDependencyGraph ISingleFileComponentRecorder.DependencyGraph => DependencyGraph;
+ IDependencyGraph ISingleFileComponentRecorder.DependencyGraph => this.DependencyGraph;
private readonly ConcurrentDictionary detectedComponentsInternal = new ConcurrentDictionary();
@@ -108,15 +108,15 @@ public class SingleFileComponentRecorder : ISingleFileComponentRecorder
public SingleFileComponentRecorder(string location, ComponentRecorder recorder, bool enableManualTrackingOfExplicitReferences, ILogger log)
{
- ManifestFileLocation = location;
+ this.ManifestFileLocation = location;
this.recorder = recorder;
this.log = log;
- DependencyGraph = new DependencyGraph(enableManualTrackingOfExplicitReferences);
+ this.DependencyGraph = new DependencyGraph(enableManualTrackingOfExplicitReferences);
}
public DetectedComponent GetComponent(string componentId)
{
- if (detectedComponentsInternal.TryGetValue(componentId, out var detectedComponent))
+ if (this.detectedComponentsInternal.TryGetValue(componentId, out var detectedComponent))
{
return detectedComponent;
}
@@ -127,7 +127,7 @@ public DetectedComponent GetComponent(string componentId)
public IReadOnlyDictionary GetDetectedComponents()
{
// Should this be immutable?
- return detectedComponentsInternal;
+ return this.detectedComponentsInternal;
}
public void RegisterUsage(
@@ -150,42 +150,42 @@ public void RegisterUsage(
#if DEBUG
if (detectedComponent.FilePaths?.Any() ?? false)
{
- log?.LogWarning("Detector should not populate DetectedComponent.FilePaths!");
+ this.log?.LogWarning("Detector should not populate DetectedComponent.FilePaths!");
}
if (detectedComponent.DependencyRoots?.Any() ?? false)
{
- log?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!");
+ this.log?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!");
}
if (detectedComponent.DevelopmentDependency.HasValue)
{
- log?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!");
+ this.log?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!");
}
#endif
- string componentId = detectedComponent.Component.Id;
+ var componentId = detectedComponent.Component.Id;
DetectedComponent storedComponent = null;
- lock (registerUsageLock)
+ lock (this.registerUsageLock)
{
- storedComponent = detectedComponentsInternal.GetOrAdd(componentId, detectedComponent);
- AddComponentToGraph(ManifestFileLocation, detectedComponent, isExplicitReferencedDependency, parentComponentId, isDevelopmentDependency, dependencyScope);
+ storedComponent = this.detectedComponentsInternal.GetOrAdd(componentId, detectedComponent);
+ this.AddComponentToGraph(this.ManifestFileLocation, detectedComponent, isExplicitReferencedDependency, parentComponentId, isDevelopmentDependency, dependencyScope);
}
}
public void AddAdditionalRelatedFile(string relatedFilePath)
{
- DependencyGraph.AddAdditionalRelatedFile(relatedFilePath);
+ this.DependencyGraph.AddAdditionalRelatedFile(relatedFilePath);
}
public IList GetAdditionalRelatedFiles()
{
- return DependencyGraph.GetAdditionalRelatedFiles().ToImmutableList();
+ return this.DependencyGraph.GetAdditionalRelatedFiles().ToImmutableList();
}
public IComponentRecorder GetParentComponentRecorder()
{
- return recorder;
+ return this.recorder;
}
private void AddComponentToGraph(
@@ -204,7 +204,7 @@ private void AddComponentToGraph(
DependencyScope = dependencyScope,
};
- DependencyGraph.AddComponent(componentNode, parentComponentId);
+ this.DependencyGraph.AddComponent(componentNode, parentComponentId);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs b/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs
index b7360c05d..0d4175a36 100644
--- a/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs
+++ b/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs
@@ -21,7 +21,7 @@ internal class DependencyGraph : IDependencyGraph
public DependencyGraph(bool enableManualTrackingOfExplicitReferences)
{
- componentNodes = new ConcurrentDictionary();
+ this.componentNodes = new ConcurrentDictionary();
this.enableManualTrackingOfExplicitReferences = enableManualTrackingOfExplicitReferences;
}
@@ -37,7 +37,7 @@ public void AddComponent(ComponentRefNode componentNode, string parentComponentI
throw new ArgumentNullException(nameof(componentNode.Id));
}
- componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) =>
+ this.componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) =>
{
currentNode.IsExplicitReferencedDependency |= componentNode.IsExplicitReferencedDependency;
@@ -55,17 +55,17 @@ public void AddComponent(ComponentRefNode componentNode, string parentComponentI
return currentNode;
});
- AddDependency(componentNode.Id, parentComponentId);
+ this.AddDependency(componentNode.Id, parentComponentId);
}
public bool Contains(string componentId)
{
- return componentNodes.ContainsKey(componentId);
+ return this.componentNodes.ContainsKey(componentId);
}
public ICollection GetDependenciesForComponent(string componentId)
{
- return componentNodes[componentId].DependencyIds;
+ return this.componentNodes[componentId].DependencyIds;
}
public ICollection GetExplicitReferencedDependencyIds(string componentId)
@@ -75,53 +75,53 @@ public ICollection GetExplicitReferencedDependencyIds(string componentId
throw new ArgumentNullException(nameof(componentId));
}
- if (!componentNodes.TryGetValue(componentId, out var componentRef))
+ if (!this.componentNodes.TryGetValue(componentId, out var componentRef))
{
throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, componentId), paramName: nameof(componentId));
}
IList explicitReferencedDependencyIds = new List();
- GetExplicitReferencedDependencies(componentRef, explicitReferencedDependencyIds, new HashSet());
+ this.GetExplicitReferencedDependencies(componentRef, explicitReferencedDependencyIds, new HashSet());
return explicitReferencedDependencyIds;
}
public void AddAdditionalRelatedFile(string additionalRelatedFile)
{
- AdditionalRelatedFiles.AddOrUpdate(additionalRelatedFile, 0, (notUsed, notUsed2) => 0);
+ this.AdditionalRelatedFiles.AddOrUpdate(additionalRelatedFile, 0, (notUsed, notUsed2) => 0);
}
public HashSet GetAdditionalRelatedFiles()
{
- return AdditionalRelatedFiles.Keys.ToImmutableHashSet().ToHashSet();
+ return this.AdditionalRelatedFiles.Keys.ToImmutableHashSet().ToHashSet();
}
public bool HasComponents()
{
- return componentNodes.Count > 0;
+ return this.componentNodes.Count > 0;
}
public bool? IsDevelopmentDependency(string componentId)
{
- return componentNodes[componentId].IsDevelopmentDependency;
+ return this.componentNodes[componentId].IsDevelopmentDependency;
}
public DependencyScope? GetDependencyScope(string componentId)
{
- return componentNodes[componentId].DependencyScope;
+ return this.componentNodes[componentId].DependencyScope;
}
public IEnumerable GetAllExplicitlyReferencedComponents()
{
- return componentNodes.Values
- .Where(componentRefNode => IsExplicitReferencedDependency(componentRefNode))
+ return this.componentNodes.Values
+ .Where(componentRefNode => this.IsExplicitReferencedDependency(componentRefNode))
.Select(componentRefNode => componentRefNode.Id);
}
private void GetExplicitReferencedDependencies(ComponentRefNode component, IList explicitReferencedDependencyIds, ISet visited)
{
- if (IsExplicitReferencedDependency(component))
+ if (this.IsExplicitReferencedDependency(component))
{
explicitReferencedDependencyIds.Add(component.Id);
}
@@ -132,15 +132,15 @@ private void GetExplicitReferencedDependencies(ComponentRefNode component, IList
{
if (!visited.Contains(parentId))
{
- GetExplicitReferencedDependencies(componentNodes[parentId], explicitReferencedDependencyIds, visited);
+ this.GetExplicitReferencedDependencies(this.componentNodes[parentId], explicitReferencedDependencyIds, visited);
}
}
}
private bool IsExplicitReferencedDependency(ComponentRefNode component)
{
- return (enableManualTrackingOfExplicitReferences && component.IsExplicitReferencedDependency) ||
- (!enableManualTrackingOfExplicitReferences && !component.DependedOnByIds.Any());
+ return (this.enableManualTrackingOfExplicitReferences && component.IsExplicitReferencedDependency) ||
+ (!this.enableManualTrackingOfExplicitReferences && !component.DependedOnByIds.Any());
}
private void AddDependency(string componentId, string parentComponentId)
@@ -150,28 +150,28 @@ private void AddDependency(string componentId, string parentComponentId)
return;
}
- if (!componentNodes.TryGetValue(parentComponentId, out var parentComponentRefNode))
+ if (!this.componentNodes.TryGetValue(parentComponentId, out var parentComponentRefNode))
{
throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, parentComponentId), nameof(parentComponentId));
}
parentComponentRefNode.DependencyIds.Add(componentId);
- componentNodes[componentId].DependedOnByIds.Add(parentComponentId);
+ this.componentNodes[componentId].DependedOnByIds.Add(parentComponentId);
}
IEnumerable IDependencyGraph.GetDependenciesForComponent(string componentId)
{
- return GetDependenciesForComponent(componentId).ToImmutableList();
+ return this.GetDependenciesForComponent(componentId).ToImmutableList();
}
IEnumerable IDependencyGraph.GetComponents()
{
- return componentNodes.Keys.ToImmutableList();
+ return this.componentNodes.Keys.ToImmutableList();
}
bool IDependencyGraph.IsComponentExplicitlyReferenced(string componentId)
{
- return IsExplicitReferencedDependency(componentNodes[componentId]);
+ return this.IsExplicitReferencedDependency(this.componentNodes[componentId]);
}
internal class ComponentRefNode
@@ -190,8 +190,8 @@ internal class ComponentRefNode
internal ComponentRefNode()
{
- DependencyIds = new HashSet();
- DependedOnByIds = new HashSet();
+ this.DependencyIds = new HashSet();
+ this.DependedOnByIds = new HashSet();
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs b/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs
index ddd7413df..37e182f03 100644
--- a/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs
+++ b/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs
@@ -1,13 +1,10 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using Microsoft.ComponentDetection.Contracts.BcdeModels;
+using Microsoft.ComponentDetection.Contracts.BcdeModels;
namespace Microsoft.ComponentDetection.Common
{
///
- /// Merges dependnecy Scope in their order of Priority.
- /// Higher priority scope, as indicated by its lower enum value is given precendence.
+ /// Merges dependnecy Scope in their order of Priority.
+ /// Higher priority scope, as indicated by its lower enum value is given precendence.
///
public class DependencyScopeComparer
{
diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs
index c01fc8fda..c7c64e240 100644
--- a/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs
+++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DigestUtility.cs
@@ -26,7 +26,7 @@ public static bool CheckDigest(string digest, bool throwError = true)
return false;
}
- string algorithm = digest.Substring(0, indexOfColon);
+ var algorithm = digest.Substring(0, indexOfColon);
if (!AlgorithmsSizes.ContainsKey(algorithm))
{
diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs
index 5ed79c7e0..0535090c1 100644
--- a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs
+++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceException.cs
@@ -16,7 +16,7 @@ public class ReferenceInvalidFormatException : DockerReferenceException
{
private const string ErrorMessage = "invalid reference format";
- public ReferenceInvalidFormatException(string reference)
+ public ReferenceInvalidFormatException(string reference)
: base(reference, ErrorMessage)
{
}
@@ -117,4 +117,4 @@ public InvalidDigestLengthError(string reference)
{
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs
index 023db51ca..140d1197f 100644
--- a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs
+++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerReferenceUtility.cs
@@ -1,7 +1,4 @@
using Microsoft.ComponentDetection.Contracts;
-using System;
-using System.Collections.Generic;
-using System.Linq;
using System.Text.RegularExpressions;
// transcribed from https://github.com/containers/image/blob/c1a5f92d0ebbf9e0bf187b3353dd400472b388eb/docker/reference/reference.go
@@ -42,7 +39,7 @@ public class DockerReferenceUtility
public static DockerReference ParseQualifiedName(string qualifiedName)
{
- Regex regexp = DockerRegex.ReferenceRegexp;
+ var regexp = DockerRegex.ReferenceRegexp;
if (!regexp.IsMatch(qualifiedName))
{
if (string.IsNullOrWhiteSpace(qualifiedName))
@@ -66,8 +63,8 @@ public static DockerReference ParseQualifiedName(string qualifiedName)
throw new ReferenceNameTooLongException(name);
}
- Reference reference = new Reference();
-
+ var reference = new Reference();
+
var nameMatch = DockerRegex.AnchoredNameRegexp.Match(name).Groups;
if (nameMatch.Count == 3)
{
@@ -96,7 +93,7 @@ public static (string, string) SplitDockerDomain(string name)
string domain;
string reminder;
- int indexOfSlash = name.IndexOf('/');
+ var indexOfSlash = name.IndexOf('/');
if (indexOfSlash == -1 || !(
name.LastIndexOf('.', indexOfSlash) != -1 ||
name.LastIndexOf(':', indexOfSlash) != -1 ||
@@ -116,7 +113,7 @@ public static (string, string) SplitDockerDomain(string name)
domain = DEFAULTDOMAIN;
}
- if (domain == DEFAULTDOMAIN && reminder.IndexOf('/') != -1)
+ if (domain == DEFAULTDOMAIN && reminder.IndexOf('/') == -1)
{
reminder = $"{OFFICIALREPOSITORYNAME}/{reminder}";
}
@@ -131,10 +128,10 @@ public static DockerReference ParseFamiliarName(string name)
throw new ReferenceNameNotCanonicalException(name);
}
- (string domain, string remainder) = SplitDockerDomain(name);
+ (var domain, var remainder) = SplitDockerDomain(name);
string remoteName;
- int tagSeparatorIndex = remainder.IndexOf(':');
+ var tagSeparatorIndex = remainder.IndexOf(':');
if (tagSeparatorIndex > -1)
{
remoteName = remainder.Substring(0, tagSeparatorIndex);
@@ -169,59 +166,7 @@ public static DockerReference ParseAll(string name)
private static DockerReference CreateDockerReference(Reference options)
{
- if (!string.IsNullOrEmpty(options.Repository) && string.IsNullOrEmpty(options.Domain))
- {
- if (!string.IsNullOrEmpty(options.Digest))
- {
- return new DigestReference
- {
- Digest = options.Digest,
- };
- }
- else
- {
- throw new ReferenceNameEmptyException(string.Empty);
- }
- }
- else if (string.IsNullOrEmpty(options.Tag))
- {
- if (string.IsNullOrEmpty(options.Digest))
- {
- return new CanonicalReference
- {
- Domain = options.Domain,
- Repository = options.Repository,
- Digest = options.Digest,
- };
- }
- else
- {
- return new RepositoryReference
- {
- Domain = options.Domain,
- Repository = options.Repository,
- };
- }
- }
- else if (string.IsNullOrEmpty(options.Digest))
- {
- return new TaggedReference
- {
- Domain = options.Domain,
- Repository = options.Repository,
- Tag = options.Tag,
- };
- }
- else
- {
- return new DualReference
- {
- Domain = options.Domain,
- Repository = options.Repository,
- Tag = options.Tag,
- Digest = options.Digest,
- };
- }
+ return DockerReference.CreateDockerReference(options.Repository, options.Domain, options.Digest, options.Tag);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs
index 780460668..1d51c6251 100644
--- a/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs
+++ b/src/Microsoft.ComponentDetection.Common/DockerReference/DockerRegex.cs
@@ -1,5 +1,3 @@
-using System;
-using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
@@ -71,10 +69,10 @@ public static Regex Capture(params Regex[] regexps)
DomainComponentRegexp,
Optional(
Repeated(
- new Regex(@"\."),
+ new Regex(@"\."),
DomainComponentRegexp)),
Optional(
- new Regex(":"),
+ new Regex(":"),
new Regex("[0-9]+")));
public static Regex AnchoredDigestRegexp = Anchored(DigestRegexp);
@@ -107,4 +105,4 @@ public static Regex Capture(params Regex[] regexps)
public static Regex AnchoredIdentifierRegexp = Anchored(IdentifierRegexp);
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/DockerService.cs b/src/Microsoft.ComponentDetection.Common/DockerService.cs
index e1bef86db..20c1606f8 100644
--- a/src/Microsoft.ComponentDetection.Common/DockerService.cs
+++ b/src/Microsoft.ComponentDetection.Common/DockerService.cs
@@ -37,7 +37,7 @@ public async Task CanPingDockerAsync(CancellationToken cancellationToken =
}
catch (Exception e)
{
- Logger.LogException(e, false);
+ this.Logger.LogException(e, false);
return false;
}
}
@@ -45,7 +45,7 @@ public async Task CanPingDockerAsync(CancellationToken cancellationToken =
public async Task CanRunLinuxContainersAsync(CancellationToken cancellationToken = default)
{
using var record = new DockerServiceSystemInfoTelemetryRecord();
- if (!await CanPingDockerAsync(cancellationToken))
+ if (!await this.CanPingDockerAsync(cancellationToken))
{
return false;
}
@@ -78,7 +78,7 @@ public async Task ImageExistsLocallyAsync(string image, CancellationToken
}
catch (Exception e)
{
- record.ExceptionMessage = e.Message;
+ record.ExceptionMessage = e.Message;
return false;
}
}
@@ -120,7 +120,7 @@ public async Task InspectImageAsync(string image, Cancellation
{
var imageInspectResponse = await Client.Images.InspectImageAsync(image, cancellationToken);
record.ImageInspectResponse = JsonConvert.SerializeObject(imageInspectResponse);
-
+
var baseImageRef = string.Empty;
var baseImageDigest = string.Empty;
@@ -128,12 +128,12 @@ public async Task InspectImageAsync(string image, Cancellation
imageInspectResponse.Config.Labels?.TryGetValue(BaseImageDigestAnnotation, out baseImageDigest);
record.BaseImageRef = baseImageRef;
- record.BaseImageDigest = baseImageDigest;
+ record.BaseImageDigest = baseImageDigest;
var layers = imageInspectResponse.RootFS?.Layers
- .Select((diffId, index) =>
+ .Select((diffId, index) =>
new DockerLayer
- {
+ {
DiffId = diffId,
LayerIndex = index,
});
@@ -165,7 +165,7 @@ public async Task InspectImageAsync(string image, Cancellation
Image = image,
Command = JsonConvert.SerializeObject(command),
};
- await TryPullImageAsync(image, cancellationToken);
+ await this.TryPullImageAsync(image, cancellationToken);
var container = await CreateContainerAsync(image, command, cancellationToken);
record.Container = JsonConvert.SerializeObject(container);
var stream = await AttachContainerAsync(container.ID, cancellationToken);
diff --git a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs
index 223e7942b..4b05e5fe9 100644
--- a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs
+++ b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs
@@ -10,7 +10,7 @@ public class EnvironmentVariableService : IEnvironmentVariableService
{
public bool DoesEnvironmentVariableExist(string name)
{
- return GetEnvironmentVariable(name) != null;
+ return this.GetEnvironmentVariable(name) != null;
}
public string GetEnvironmentVariable(string name)
@@ -27,7 +27,7 @@ public string GetEnvironmentVariable(string name)
public bool IsEnvironmentVariableValueTrue(string name)
{
- _ = bool.TryParse(GetEnvironmentVariable(name), out bool result);
+ _ = bool.TryParse(this.GetEnvironmentVariable(name), out var result);
return result;
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs b/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs
index 8ce3c554a..d7e9dacdb 100644
--- a/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs
+++ b/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs
@@ -34,7 +34,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu
{
if (!root.Exists)
{
- Logger?.LogError($"Root directory doesn't exist: {root.FullName}");
+ this.Logger?.LogError($"Root directory doesn't exist: {root.FullName}");
s.OnCompleted();
return Task.CompletedTask;
}
@@ -52,7 +52,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu
var sw = Stopwatch.StartNew();
- Logger?.LogInfo($"Starting enumeration of {root.FullName}");
+ this.Logger?.LogInfo($"Starting enumeration of {root.FullName}");
var fileCount = 0;
var directoryCount = 0;
@@ -73,7 +73,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu
if (di.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
- var realPath = PathUtilityService.ResolvePhysicalPath(di.FullName);
+ var realPath = this.PathUtilityService.ResolvePhysicalPath(di.FullName);
realDirectory = new DirectoryInfo(realPath);
}
@@ -91,7 +91,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu
return true;
});
- var initialIterator = new FileSystemEnumerable(root.FullName, Transform, new EnumerationOptions()
+ var initialIterator = new FileSystemEnumerable(root.FullName, this.Transform, new EnumerationOptions()
{
RecurseSubdirectories = false,
IgnoreInaccessible = true,
@@ -145,7 +145,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu
var scan = new ActionBlock(
di =>
{
- var enumerator = new FileSystemEnumerable(di.FullName, Transform, new EnumerationOptions()
+ var enumerator = new FileSystemEnumerable(di.FullName, this.Transform, new EnumerationOptions()
{
RecurseSubdirectories = true,
IgnoreInaccessible = true,
@@ -188,7 +188,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu
}, () =>
{
sw.Stop();
- Logger?.LogInfo($"Enumerated {fileCount} files and {directoryCount} directories in {sw.Elapsed}");
+ this.Logger?.LogInfo($"Enumerated {fileCount} files and {directoryCount} directories in {sw.Elapsed}");
s.OnCompleted();
});
});
@@ -201,13 +201,13 @@ private FileSystemInfo Transform(ref FileSystemEntry entry)
private IObservable CreateDirectoryWalker(DirectoryInfo di, ExcludeDirectoryPredicate directoryExclusionPredicate, int minimumConnectionCount, IEnumerable filePatterns)
{
- return GetDirectoryScanner(di, new ConcurrentDictionary(), directoryExclusionPredicate, filePatterns, true).Replay() // Returns a replay subject which will republish anything found to new subscribers.
+ return this.GetDirectoryScanner(di, new ConcurrentDictionary(), directoryExclusionPredicate, filePatterns, true).Replay() // Returns a replay subject which will republish anything found to new subscribers.
.AutoConnect(minimumConnectionCount); // Specifies that this connectable observable should start when minimumConnectionCount subscribe.
}
private bool MatchesAnyPattern(FileInfo fi, params string[] searchPatterns)
{
- return searchPatterns != null && searchPatterns.Any(sp => PathUtilityService.MatchesPattern(sp, fi.Name));
+ return searchPatterns != null && searchPatterns.Any(sp => this.PathUtilityService.MatchesPattern(sp, fi.Name));
}
///
@@ -219,22 +219,22 @@ private bool MatchesAnyPattern(FileInfo fi, params string[] searchPatterns)
/// Pattern used to filter files.
public void Initialize(DirectoryInfo root, ExcludeDirectoryPredicate directoryExclusionPredicate, int minimumConnectionCount, IEnumerable filePatterns = null)
{
- pendingScans.GetOrAdd(root, new Lazy>(() => CreateDirectoryWalker(root, directoryExclusionPredicate, minimumConnectionCount, filePatterns)));
+ this.pendingScans.GetOrAdd(root, new Lazy>(() => this.CreateDirectoryWalker(root, directoryExclusionPredicate, minimumConnectionCount, filePatterns)));
}
public IObservable Subscribe(DirectoryInfo root, IEnumerable patterns)
{
var patternArray = patterns.ToArray();
- if (pendingScans.TryGetValue(root, out var scannerObservable))
+ if (this.pendingScans.TryGetValue(root, out var scannerObservable))
{
- Logger.LogVerbose(string.Join(":", patterns));
+ this.Logger.LogVerbose(string.Join(":", patterns));
var inner = scannerObservable.Value.Where(fsi =>
{
if (fsi is FileInfo fi)
{
- return MatchesAnyPattern(fi, patternArray);
+ return this.MatchesAnyPattern(fi, patternArray);
}
else
{
@@ -250,7 +250,7 @@ public IObservable Subscribe(DirectoryInfo root, IEnumerable GetFilteredComponentStreamObservable(DirectoryInfo root, IEnumerable patterns, IComponentRecorder componentRecorder)
{
- var observable = Subscribe(root, patterns).OfType().SelectMany(f => patterns.Select(sp => new
+ var observable = this.Subscribe(root, patterns).OfType().SelectMany(f => patterns.Select(sp => new
{
SearchPattern = sp,
File = f,
@@ -259,11 +259,11 @@ public IObservable GetFilteredComponentStreamObservable(Director
var searchPattern = x.SearchPattern;
var fileName = x.File.Name;
- return PathUtilityService.MatchesPattern(searchPattern, fileName);
+ return this.PathUtilityService.MatchesPattern(searchPattern, fileName);
}).Where(x => x.File.Exists)
.Select(x =>
{
- var lazyComponentStream = new LazyComponentStream(x.File, x.SearchPattern, Logger);
+ var lazyComponentStream = new LazyComponentStream(x.File, x.SearchPattern, this.Logger);
return new ProcessRequest
{
ComponentStream = lazyComponentStream,
@@ -276,7 +276,7 @@ public IObservable GetFilteredComponentStreamObservable(Director
public void StartScan(DirectoryInfo root)
{
- if (pendingScans.TryRemove(root, out var scannerObservable))
+ if (this.pendingScans.TryRemove(root, out var scannerObservable))
{
// scannerObservable.Connect();
}
@@ -286,7 +286,7 @@ public void StartScan(DirectoryInfo root)
public void Reset()
{
- pendingScans.Clear();
+ this.pendingScans.Clear();
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/FileWritingService.cs b/src/Microsoft.ComponentDetection.Common/FileWritingService.cs
index a39b47211..fc44ad6e6 100644
--- a/src/Microsoft.ComponentDetection.Common/FileWritingService.cs
+++ b/src/Microsoft.ComponentDetection.Common/FileWritingService.cs
@@ -23,14 +23,14 @@ public void Init(string basePath)
throw new InvalidUserInputException($"The path {basePath} does not exist.", new DirectoryNotFoundException());
}
- BasePath = string.IsNullOrEmpty(basePath) ? Path.GetTempPath() : basePath;
+ this.BasePath = string.IsNullOrEmpty(basePath) ? Path.GetTempPath() : basePath;
}
public void AppendToFile(string relativeFilePath, string text)
{
- relativeFilePath = ResolveFilePath(relativeFilePath);
+ relativeFilePath = this.ResolveFilePath(relativeFilePath);
- lock (lockObject)
+ lock (this.lockObject)
{
File.AppendAllText(relativeFilePath, text);
}
@@ -38,9 +38,9 @@ public void AppendToFile(string relativeFilePath, string text)
public void WriteFile(string relativeFilePath, string text)
{
- relativeFilePath = ResolveFilePath(relativeFilePath);
+ relativeFilePath = this.ResolveFilePath(relativeFilePath);
- lock (lockObject)
+ lock (this.lockObject)
{
File.WriteAllText(relativeFilePath, text);
}
@@ -53,19 +53,19 @@ public void WriteFile(FileInfo absolutePath, string text)
public string ResolveFilePath(string relativeFilePath)
{
- EnsureInit();
+ this.EnsureInit();
if (relativeFilePath.Contains("{timestamp}"))
{
- relativeFilePath = relativeFilePath.Replace("{timestamp}", timestamp);
+ relativeFilePath = relativeFilePath.Replace("{timestamp}", this.timestamp);
}
- relativeFilePath = Path.Combine(BasePath, relativeFilePath);
+ relativeFilePath = Path.Combine(this.BasePath, relativeFilePath);
return relativeFilePath;
}
private void EnsureInit()
{
- if (string.IsNullOrEmpty(BasePath))
+ if (string.IsNullOrEmpty(this.BasePath))
{
throw new InvalidOperationException("Base path has not yet been initialized in File Writing Service!");
}
diff --git a/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs b/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs
index 5b15d112d..1baae8558 100644
--- a/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs
+++ b/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs
@@ -14,21 +14,21 @@ private byte[] SafeOpenFile()
{
try
{
- using var fs = fileInfo.OpenRead();
+ using var fs = this.fileInfo.OpenRead();
- var buffer = new byte[fileInfo.Length];
- fs.Read(buffer, 0, (int)fileInfo.Length);
+ var buffer = new byte[this.fileInfo.Length];
+ fs.Read(buffer, 0, (int)this.fileInfo.Length);
return buffer;
}
catch (UnauthorizedAccessException)
{
- logger?.LogWarning($"Unauthorized access exception caught when trying to open {fileInfo.FullName}");
+ this.logger?.LogWarning($"Unauthorized access exception caught when trying to open {this.fileInfo.FullName}");
}
catch (Exception e)
{
- logger?.LogWarning($"Unhandled exception caught when trying to open {fileInfo.FullName}");
- logger?.LogException(e, isError: false);
+ this.logger?.LogWarning($"Unhandled exception caught when trying to open {this.fileInfo.FullName}");
+ this.logger?.LogException(e, isError: false);
}
return new byte[0];
@@ -36,14 +36,14 @@ private byte[] SafeOpenFile()
public LazyComponentStream(FileInfo fileInfo, string pattern, ILogger logger)
{
- Pattern = pattern;
- Location = fileInfo.FullName;
+ this.Pattern = pattern;
+ this.Location = fileInfo.FullName;
this.fileInfo = fileInfo;
this.logger = logger;
- fileBuffer = new Lazy(SafeOpenFile);
+ this.fileBuffer = new Lazy(this.SafeOpenFile);
}
- public Stream Stream => new MemoryStream(fileBuffer.Value);
+ public Stream Stream => new MemoryStream(this.fileBuffer.Value);
public string Pattern { get; set; }
diff --git a/src/Microsoft.ComponentDetection.Common/Logger.cs b/src/Microsoft.ComponentDetection.Common/Logger.cs
index fc2977e63..dfed734c5 100644
--- a/src/Microsoft.ComponentDetection.Common/Logger.cs
+++ b/src/Microsoft.ComponentDetection.Common/Logger.cs
@@ -27,45 +27,45 @@ public class Logger : ILogger
public void Init(VerbosityMode verbosity)
{
- WriteToFile = true;
- Verbosity = verbosity;
+ this.WriteToFile = true;
+ this.Verbosity = verbosity;
try
{
- FileWritingService.WriteFile(LogRelativePath, string.Empty);
- LogInfo($"Log file: {FileWritingService.ResolveFilePath(LogRelativePath)}");
+ this.FileWritingService.WriteFile(LogRelativePath, string.Empty);
+ this.LogInfo($"Log file: {this.FileWritingService.ResolveFilePath(LogRelativePath)}");
}
catch (Exception)
{
- WriteToFile = false;
- LogError("There was an issue writing to the log file, for the remainder of execution verbose output will be written to the console.");
- Verbosity = VerbosityMode.Verbose;
+ this.WriteToFile = false;
+ this.LogError("There was an issue writing to the log file, for the remainder of execution verbose output will be written to the console.");
+ this.Verbosity = VerbosityMode.Verbose;
}
}
public void LogCreateLoggingGroup()
{
- PrintToConsole(NewLine, VerbosityMode.Normal);
- AppendToFile(NewLine);
+ this.PrintToConsole(NewLine, VerbosityMode.Normal);
+ this.AppendToFile(NewLine);
}
public void LogWarning(string message)
{
- LogInternal("WARN", message);
+ this.LogInternal("WARN", message);
}
public void LogInfo(string message)
{
- LogInternal("INFO", message);
+ this.LogInternal("INFO", message);
}
public void LogVerbose(string message)
{
- LogInternal("VERBOSE", message, VerbosityMode.Verbose);
+ this.LogInternal("VERBOSE", message, VerbosityMode.Verbose);
}
public void LogError(string message)
{
- LogInternal("ERROR", message, VerbosityMode.Quiet);
+ this.LogInternal("ERROR", message, VerbosityMode.Quiet);
}
private void LogInternal(string prefix, string message, VerbosityMode verbosity = VerbosityMode.Normal)
@@ -73,15 +73,15 @@ private void LogInternal(string prefix, string message, VerbosityMode verbosity
var formattedPrefix = string.IsNullOrWhiteSpace(prefix) ? string.Empty : $"[{prefix}] ";
var text = $"{formattedPrefix}{message} {NewLine}";
- PrintToConsole(text, verbosity);
- AppendToFile(text);
+ this.PrintToConsole(text, verbosity);
+ this.AppendToFile(text);
}
public void LogFailedReadingFile(string filePath, Exception e)
{
- PrintToConsole(NewLine, VerbosityMode.Verbose);
- LogFailedProcessingFile(filePath);
- LogException(e, isError: false);
+ this.PrintToConsole(NewLine, VerbosityMode.Verbose);
+ this.LogFailedProcessingFile(filePath);
+ this.LogException(e, isError: false);
using var record = new FailedReadingFileRecord
{
FilePath = filePath,
@@ -97,7 +97,7 @@ public void LogException(
[CallerMemberName] string callerMemberName = "",
[CallerLineNumber] int callerLineNumber = 0)
{
- string tag = isError ? "[ERROR]" : "[INFO]";
+ var tag = isError ? "[ERROR]" : "[INFO]";
var fullExceptionText = $"{tag} Exception encountered." + NewLine +
$"CallerMember: [{callerMemberName} : {callerLineNumber}]" + NewLine +
@@ -109,45 +109,45 @@ public void LogException(
if (isError)
{
- PrintToConsole(consoleText, VerbosityMode.Quiet);
+ this.PrintToConsole(consoleText, VerbosityMode.Quiet);
}
else
{
- PrintToConsole(consoleText, VerbosityMode.Verbose);
+ this.PrintToConsole(consoleText, VerbosityMode.Verbose);
}
- AppendToFile(fullExceptionText);
+ this.AppendToFile(fullExceptionText);
}
// TODO: All these vso specific logs should go away
public void LogBuildWarning(string message)
{
- PrintToConsole($"##vso[task.LogIssue type=warning;]{message}{NewLine}", VerbosityMode.Quiet);
+ this.PrintToConsole($"##vso[task.LogIssue type=warning;]{message}{NewLine}", VerbosityMode.Quiet);
}
public void LogBuildError(string message)
{
- PrintToConsole($"##vso[task.LogIssue type=error;]{message}{NewLine}", VerbosityMode.Quiet);
+ this.PrintToConsole($"##vso[task.LogIssue type=error;]{message}{NewLine}", VerbosityMode.Quiet);
}
private void LogFailedProcessingFile(string filePath)
{
- LogVerbose($"Could not read component details from file {filePath} {NewLine}");
+ this.LogVerbose($"Could not read component details from file {filePath} {NewLine}");
}
private void AppendToFile(string text)
{
- if (WriteToFile)
+ if (this.WriteToFile)
{
- FileWritingService.AppendToFile(LogRelativePath, text);
+ this.FileWritingService.AppendToFile(LogRelativePath, text);
}
}
private void PrintToConsole(string text, VerbosityMode minVerbosity)
{
- if (Verbosity >= minVerbosity)
+ if (this.Verbosity >= minVerbosity)
{
- ConsoleWriter.Write(text);
+ this.ConsoleWriter.Write(text);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj b/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj
index 8df30202a..57f866733 100644
--- a/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj
+++ b/src/Microsoft.ComponentDetection.Common/Microsoft.ComponentDetection.Common.csproj
@@ -1,5 +1,5 @@
-
+
@@ -29,4 +29,4 @@
-
\ No newline at end of file
+
diff --git a/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs b/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs
index 4a93e88ea..7c75e3ea7 100644
--- a/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs
+++ b/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs
@@ -34,18 +34,18 @@ public bool IsRunningOnWindowsContainer
{
get
{
- if (!isRunningOnWindowsContainer.HasValue)
+ if (!this.isRunningOnWindowsContainer.HasValue)
{
- lock (isRunningOnWindowsContainerLock)
+ lock (this.isRunningOnWindowsContainerLock)
{
- if (!isRunningOnWindowsContainer.HasValue)
+ if (!this.isRunningOnWindowsContainer.HasValue)
{
- isRunningOnWindowsContainer = CheckIfRunningOnWindowsContainer();
+ this.isRunningOnWindowsContainer = this.CheckIfRunningOnWindowsContainer();
}
}
}
- return isRunningOnWindowsContainer.Value;
+ return this.isRunningOnWindowsContainer.Value;
}
}
@@ -113,11 +113,11 @@ public string ResolvePhysicalPath(string path)
{
if (IsWindows)
{
- return ResolvePhysicalPathWindows(path);
+ return this.ResolvePhysicalPathWindows(path);
}
else if (IsLinux)
{
- return ResolvePhysicalPathLinux(path);
+ return this.ResolvePhysicalPathLinux(path);
}
return path;
@@ -130,27 +130,27 @@ public string ResolvePhysicalPathWindows(string path)
throw new PlatformNotSupportedException("Attempted to call a function that makes windows-only SDK calls");
}
- if (IsRunningOnWindowsContainer)
+ if (this.IsRunningOnWindowsContainer)
{
return path;
}
- if (resolvedPaths.TryGetValue(path, out string cachedPath))
+ if (this.resolvedPaths.TryGetValue(path, out var cachedPath))
{
return cachedPath;
}
- DirectoryInfo symlink = new DirectoryInfo(path);
+ var symlink = new DirectoryInfo(path);
- using SafeFileHandle directoryHandle = CreateFile(symlink.FullName, 0, 2, IntPtr.Zero, CreationDispositionRead, FileFlagBackupSemantics, IntPtr.Zero);
+ using var directoryHandle = CreateFile(symlink.FullName, 0, 2, IntPtr.Zero, CreationDispositionRead, FileFlagBackupSemantics, IntPtr.Zero);
if (directoryHandle.IsInvalid)
{
return path;
}
- StringBuilder resultBuilder = new StringBuilder(InitalPathBufferSize);
- int mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuilder, resultBuilder.Capacity, 0);
+ var resultBuilder = new StringBuilder(InitalPathBufferSize);
+ var mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), resultBuilder, resultBuilder.Capacity, 0);
// If GetFinalPathNameByHandle needs a bigger buffer, it will tell us the size it needs (including the null terminator) in finalPathNameResultCode
if (mResult > InitalPathBufferSize)
@@ -164,11 +164,11 @@ public string ResolvePhysicalPathWindows(string path)
return path;
}
- string result = resultBuilder.ToString();
+ var result = resultBuilder.ToString();
result = result.StartsWith(LongPathPrefix) ? result.Substring(LongPathPrefix.Length) : result;
- resolvedPaths.TryAdd(path, result);
+ this.resolvedPaths.TryAdd(path, result);
return result;
}
@@ -180,7 +180,7 @@ public string ResolvePhysicalPathLinux(string path)
throw new PlatformNotSupportedException("Attempted to call a function that makes linux-only library calls");
}
- IntPtr pointer = IntPtr.Zero;
+ var pointer = IntPtr.Zero;
try
{
pointer = RealPathLinux(path, IntPtr.Zero);
@@ -197,7 +197,7 @@ public string ResolvePhysicalPathLinux(string path)
}
catch (Exception ex)
{
- Logger.LogException(ex, isError: false, printException: true);
+ this.Logger.LogException(ex, isError: false, printException: true);
return path;
}
finally
@@ -218,7 +218,7 @@ private bool CheckIfRunningOnWindowsContainer()
// This isn't the best way to do this in C#, but netstandard doesn't seem to support the service api calls
// that we need to do this without shelling out
- Process process = new Process()
+ var process = new Process()
{
StartInfo = new ProcessStartInfo
{
@@ -231,7 +231,7 @@ private bool CheckIfRunningOnWindowsContainer()
},
};
- StringBuilder sb = new StringBuilder();
+ var sb = new StringBuilder();
process.Start();
while (!process.HasExited)
@@ -244,7 +244,7 @@ private bool CheckIfRunningOnWindowsContainer()
if (sb.ToString().Contains("Container Execution Agent"))
{
- Logger.LogWarning("Detected execution in a Windows container. Currently windows containers < 1809 do not support symlinks well, so disabling symlink resolution/dedupe behavior");
+ this.Logger.LogWarning("Detected execution in a Windows container. Currently windows containers < 1809 do not support symlinks well, so disabling symlink resolution/dedupe behavior");
return true;
}
else
diff --git a/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs b/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs
index e299f3e00..ca9625104 100644
--- a/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs
+++ b/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs
@@ -12,11 +12,11 @@ public static class PatternMatchingUtility
public static FilePatternMatcher GetFilePatternMatcher(IEnumerable patterns)
{
- var ordinalComparison = Expression.Constant(System.StringComparison.Ordinal, typeof(System.StringComparison));
- var asSpan = typeof(System.MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(string) }, new ParameterModifier[0]);
- var equals = typeof(System.MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]);
- var startsWith = typeof(System.MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]);
- var endsWith = typeof(System.MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]);
+ var ordinalComparison = Expression.Constant(StringComparison.Ordinal, typeof(StringComparison));
+ var asSpan = typeof(MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(string) }, new ParameterModifier[0]);
+ var equals = typeof(MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]);
+ var startsWith = typeof(MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]);
+ var endsWith = typeof(MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]);
var predicates = new List();
var left = Expression.Parameter(typeof(ReadOnlySpan), "fileName");
@@ -53,4 +53,4 @@ public static FilePatternMatcher GetFilePatternMatcher(IEnumerable patte
return func;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs b/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs
index 08908f0d6..08bb65d5d 100644
--- a/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs
+++ b/src/Microsoft.ComponentDetection.Common/Resources.Designer.cs
@@ -10,8 +10,8 @@
namespace Microsoft.ComponentDetection.Common {
using System;
-
-
+
+
///
/// A strongly-typed resource class, for looking up localized strings, etc.
///
@@ -23,15 +23,15 @@ namespace Microsoft.ComponentDetection.Common {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
-
+
private static global::System.Resources.ResourceManager resourceMan;
-
+
private static global::System.Globalization.CultureInfo resourceCulture;
-
+
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
-
+
///
/// Returns the cached ResourceManager instance used by this class.
///
@@ -45,7 +45,7 @@ internal Resources() {
return resourceMan;
}
}
-
+
///
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
@@ -59,7 +59,7 @@ internal Resources() {
resourceCulture = value;
}
}
-
+
///
/// Looks up a localized string similar to The component object does not have a componentId specified.
///
@@ -68,7 +68,7 @@ internal static string MissingComponentId {
return ResourceManager.GetString("MissingComponentId", resourceCulture);
}
}
-
+
///
/// Looks up a localized string similar to Node with id {0} has not be inserted in the dependency graph.
///
diff --git a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs
index 3cee65b90..6e2aef8e9 100644
--- a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs
+++ b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs
@@ -29,9 +29,9 @@ public SafeFileEnumerable(DirectoryInfo directory, IEnumerable searchPat
this.directoryExclusionPredicate = directoryExclusionPredicate;
this.recursivelyScanDirectories = recursivelyScanDirectories;
this.pathUtilityService = pathUtilityService;
- enumeratedDirectories = previouslyEnumeratedDirectories;
+ this.enumeratedDirectories = previouslyEnumeratedDirectories;
- enumerationOptions = new EnumerationOptions()
+ this.enumerationOptions = new EnumerationOptions()
{
IgnoreInaccessible = true,
RecurseSubdirectories = this.recursivelyScanDirectories,
@@ -48,9 +48,9 @@ public SafeFileEnumerable(DirectoryInfo directory, Func fileMatc
public IEnumerator GetEnumerator()
{
- var previouslyEnumeratedDirectories = enumeratedDirectories ?? new HashSet();
+ var previouslyEnumeratedDirectories = this.enumeratedDirectories ?? new HashSet();
- var fse = new FileSystemEnumerable(directory.FullName, (ref FileSystemEntry entry) =>
+ var fse = new FileSystemEnumerable(this.directory.FullName, (ref FileSystemEntry entry) =>
{
if (!(entry.ToFileSystemInfo() is FileInfo fi))
{
@@ -58,7 +58,7 @@ public IEnumerator GetEnumerator()
}
var foundPattern = entry.FileName.ToString();
- foreach (var searchPattern in searchPatterns)
+ foreach (var searchPattern in this.searchPatterns)
{
if (PathUtilityService.MatchesPattern(searchPattern, ref entry))
{
@@ -67,7 +67,7 @@ public IEnumerator GetEnumerator()
}
return new MatchedFile() { File = fi, Pattern = foundPattern };
- }, enumerationOptions)
+ }, this.enumerationOptions)
{
ShouldIncludePredicate = (ref FileSystemEntry entry) =>
{
@@ -76,7 +76,7 @@ public IEnumerator GetEnumerator()
return false;
}
- foreach (var searchPattern in searchPatterns)
+ foreach (var searchPattern in this.searchPatterns)
{
if (PathUtilityService.MatchesPattern(searchPattern, ref entry))
{
@@ -88,7 +88,7 @@ public IEnumerator GetEnumerator()
},
ShouldRecursePredicate = (ref FileSystemEntry entry) =>
{
- if (!recursivelyScanDirectories)
+ if (!this.recursivelyScanDirectories)
{
return false;
}
@@ -99,7 +99,7 @@ public IEnumerator GetEnumerator()
if (entry.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
- var realPath = pathUtilityService.ResolvePhysicalPath(targetPath);
+ var realPath = this.pathUtilityService.ResolvePhysicalPath(targetPath);
seenPreviously = previouslyEnumeratedDirectories.Contains(realPath);
previouslyEnumeratedDirectories.Add(realPath);
@@ -118,12 +118,12 @@ public IEnumerator GetEnumerator()
if (seenPreviously)
{
- logger.LogVerbose($"Encountered real path {targetPath} before. Short-Circuiting directory traversal");
+ this.logger.LogVerbose($"Encountered real path {targetPath} before. Short-Circuiting directory traversal");
return false;
}
// This is actually a *directory* name (not FileName) and the directory containing that directory.
- if (entry.IsDirectory && directoryExclusionPredicate != null && directoryExclusionPredicate(entry.FileName, entry.Directory))
+ if (entry.IsDirectory && this.directoryExclusionPredicate != null && this.directoryExclusionPredicate(entry.FileName, entry.Directory))
{
return false;
}
@@ -134,7 +134,7 @@ public IEnumerator GetEnumerator()
foreach (var file in fse)
{
- if (fileMatchingPredicate == null || fileMatchingPredicate(file.File))
+ if (this.fileMatchingPredicate == null || this.fileMatchingPredicate(file.File))
{
yield return file;
}
@@ -143,7 +143,7 @@ public IEnumerator GetEnumerator()
IEnumerator IEnumerable.GetEnumerator()
{
- return GetEnumerator();
+ return this.GetEnumerator();
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs
index 541793b08..b528d73c9 100644
--- a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs
+++ b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs
@@ -17,7 +17,7 @@ public class SafeFileEnumerableFactory : ISafeFileEnumerableFactory
public IEnumerable CreateSafeFileEnumerable(DirectoryInfo directory, IEnumerable searchPatterns, ExcludeDirectoryPredicate directoryExclusionPredicate)
{
- return new SafeFileEnumerable(directory, searchPatterns, Logger, PathUtilityService, directoryExclusionPredicate);
+ return new SafeFileEnumerable(directory, searchPatterns, this.Logger, this.PathUtilityService, directoryExclusionPredicate);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs
index a6e1c5260..493f12bc3 100644
--- a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs
+++ b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs
@@ -19,7 +19,7 @@ public class TabularStringFormat
public TabularStringFormat(IList columns, char horizontalLineChar = DefaultHorizontalLineChar, char verticalLineChar = DefaultVerticalLineChar, string tableTitle = null)
{
this.columns = columns;
- totalWidth = columns.Count + 1 + columns.Sum(x => x.Width);
+ this.totalWidth = columns.Count + 1 + columns.Sum(x => x.Width);
this.horizontalLineChar = horizontalLineChar;
this.verticalLineChar = verticalLineChar;
this.tableTitle = tableTitle;
@@ -27,40 +27,40 @@ public TabularStringFormat(IList columns, char horizontalLineChar = Defa
public string GenerateString(IEnumerable> rows)
{
- StringBuilder sb = new StringBuilder();
- if (!string.IsNullOrWhiteSpace(tableTitle))
+ var sb = new StringBuilder();
+ if (!string.IsNullOrWhiteSpace(this.tableTitle))
{
- PrintTitleSection(sb);
+ this.PrintTitleSection(sb);
}
else
{
- WriteFlatLine(sb, false);
+ this.WriteFlatLine(sb, false);
}
- sb.Append(verticalLineChar);
- foreach (var column in columns)
+ sb.Append(this.verticalLineChar);
+ foreach (var column in this.columns)
{
sb.Append(column.Header.PadRight(column.Width));
- sb.Append(verticalLineChar);
+ sb.Append(this.verticalLineChar);
}
- WriteFlatLine(sb);
+ this.WriteFlatLine(sb);
foreach (var row in rows)
{
- sb.Append(verticalLineChar);
- if (row.Count != columns.Count)
+ sb.Append(this.verticalLineChar);
+ if (row.Count != this.columns.Count)
{
throw new InvalidOperationException("All rows must have length equal to the number of columns present.");
}
- for (var i = 0; i < columns.Count; i++)
+ for (var i = 0; i < this.columns.Count; i++)
{
- var dataString = columns[i].Format != null ? string.Format(columns[i].Format, row[i]) : row[i].ToString();
- sb.Append(dataString.PadRight(columns[i].Width));
- sb.Append(verticalLineChar);
+ var dataString = this.columns[i].Format != null ? string.Format(this.columns[i].Format, row[i]) : row[i].ToString();
+ sb.Append(dataString.PadRight(this.columns[i].Width));
+ sb.Append(this.verticalLineChar);
}
- WriteFlatLine(sb);
+ this.WriteFlatLine(sb);
}
return sb.ToString();
@@ -68,37 +68,37 @@ public string GenerateString(IEnumerable> rows)
private void PrintTitleSection(StringBuilder sb)
{
- WriteFlatLine(sb, false);
- var tableWidth = columns.Sum(column => column.Width);
- sb.Append(verticalLineChar);
- sb.Append(tableTitle.PadRight(tableWidth + columns.Count - 1));
- sb.Append(verticalLineChar);
+ this.WriteFlatLine(sb, false);
+ var tableWidth = this.columns.Sum(column => column.Width);
+ sb.Append(this.verticalLineChar);
+ sb.Append(this.tableTitle.PadRight(tableWidth + this.columns.Count - 1));
+ sb.Append(this.verticalLineChar);
sb.AppendLine();
- sb.Append(verticalLineChar);
- for (var i = 0; i < columns.Count - 1; i++)
+ sb.Append(this.verticalLineChar);
+ for (var i = 0; i < this.columns.Count - 1; i++)
{
- sb.Append(string.Empty.PadRight(columns[i].Width, horizontalLineChar));
- sb.Append(horizontalLineChar);
+ sb.Append(string.Empty.PadRight(this.columns[i].Width, this.horizontalLineChar));
+ sb.Append(this.horizontalLineChar);
}
- sb.Append(string.Empty.PadRight(columns[columns.Count - 1].Width, horizontalLineChar));
- sb.Append(verticalLineChar);
+ sb.Append(string.Empty.PadRight(this.columns[this.columns.Count - 1].Width, this.horizontalLineChar));
+ sb.Append(this.verticalLineChar);
sb.AppendLine();
}
private void WriteFlatLine(StringBuilder sb, bool withPipes = true)
{
- var splitCharacter = withPipes ? verticalLineChar : horizontalLineChar;
+ var splitCharacter = withPipes ? this.verticalLineChar : this.horizontalLineChar;
sb.AppendLine();
sb.Append(splitCharacter);
- for (var i = 0; i < columns.Count; i++)
+ for (var i = 0; i < this.columns.Count; i++)
{
- sb.Append(string.Empty.PadRight(columns[i].Width, horizontalLineChar));
+ sb.Append(string.Empty.PadRight(this.columns[i].Width, this.horizontalLineChar));
sb.Append(splitCharacter);
}
sb.AppendLine();
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs
index 3b786a00f..7314acd12 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs
@@ -8,7 +8,7 @@ public class TelemetryServiceAttribute : Attribute
public TelemetryServiceAttribute(string serviceType)
{
- ServiceType = serviceType;
+ this.ServiceType = serviceType;
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs
index 3eec11a5e..6dfec5e82 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs
@@ -27,12 +27,12 @@ internal class CommandLineTelemetryService : ITelemetryService
public void Flush()
{
- FileWritingService.WriteFile(TelemetryRelativePath, JsonConvert.SerializeObject(records));
+ this.FileWritingService.WriteFile(TelemetryRelativePath, JsonConvert.SerializeObject(records));
}
public void PostRecord(IDetectionTelemetryRecord record)
{
- if (telemetryMode != TelemetryMode.Disabled)
+ if (this.telemetryMode != TelemetryMode.Disabled)
{
var jsonRecord = JObject.FromObject(record);
jsonRecord.Add("Timestamp", DateTime.UtcNow);
@@ -40,16 +40,16 @@ public void PostRecord(IDetectionTelemetryRecord record)
records.Enqueue(jsonRecord);
- if (telemetryMode == TelemetryMode.Debug)
+ if (this.telemetryMode == TelemetryMode.Debug)
{
- Logger.LogInfo(jsonRecord.ToString());
+ this.Logger.LogInfo(jsonRecord.ToString());
}
}
}
public void SetMode(TelemetryMode mode)
{
- telemetryMode = mode;
+ this.telemetryMode = mode;
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs
index b303df421..f7cb52677 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs
@@ -15,15 +15,15 @@ public abstract class BaseDetectionTelemetryRecord : IDetectionTelemetryRecord
protected BaseDetectionTelemetryRecord()
{
- stopwatch.Start();
+ this.stopwatch.Start();
}
public void StopExecutionTimer()
{
- if (stopwatch.IsRunning)
+ if (this.stopwatch.IsRunning)
{
- stopwatch.Stop();
- ExecutionTime = stopwatch.Elapsed;
+ this.stopwatch.Stop();
+ this.ExecutionTime = this.stopwatch.Elapsed;
}
}
@@ -31,21 +31,21 @@ public void StopExecutionTimer()
protected virtual void Dispose(bool disposing)
{
- if (!disposedValue)
+ if (!this.disposedValue)
{
if (disposing)
{
- StopExecutionTimer();
+ this.StopExecutionTimer();
TelemetryRelay.Instance.PostTelemetryRecord(this);
}
- disposedValue = true;
+ this.disposedValue = true;
}
}
public void Dispose()
{
- Dispose(true);
+ this.Dispose(true);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs
index 45650e3cf..4b47a1884 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs
@@ -19,23 +19,23 @@ public class CommandLineInvocationTelemetryRecord : BaseDetectionTelemetryRecord
internal void Track(CommandLineExecutionResult result, string path, string parameters)
{
- ExitCode = result.ExitCode;
- StandardError = result.StdErr;
- TrackCommon(path, parameters);
+ this.ExitCode = result.ExitCode;
+ this.StandardError = result.StdErr;
+ this.TrackCommon(path, parameters);
}
internal void Track(Exception ex, string path, string parameters)
{
- ExitCode = -1;
- UnhandledException = ex.ToString();
- TrackCommon(path, parameters);
+ this.ExitCode = -1;
+ this.UnhandledException = ex.ToString();
+ this.TrackCommon(path, parameters);
}
private void TrackCommon(string path, string parameters)
{
- PathThatWasRan = path;
- Parameters = parameters;
- StopExecutionTimer();
+ this.PathThatWasRan = path;
+ this.Parameters = parameters;
+ this.StopExecutionTimer();
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs
index 3b599bdc3..57d986b22 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs
@@ -10,8 +10,8 @@ public class DetectedComponentScopeRecord : BaseDetectionTelemetryRecord
[MethodImpl(MethodImplOptions.Synchronized)]
public void IncrementProvidedScopeCount()
- {
- MavenProvidedScopeCount++;
+ {
+ this.MavenProvidedScopeCount++;
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs
index 76ed90104..16fe97210 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceImageExistsLocallyTelemetryRecord.cs
@@ -3,11 +3,11 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records
public class DockerServiceImageExistsLocallyTelemetryRecord : BaseDetectionTelemetryRecord
{
public override string RecordName => "DockerServiceImageExistsLocally";
-
+
public string Image { get; set; }
-
+
public string ImageInspectResponse { get; set; }
-
+
public string ExceptionMessage { get; set; }
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs
index ee5b0ce79..7ec37c2f2 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceInspectImageTelemetryRecord.cs
@@ -9,7 +9,7 @@ public class DockerServiceInspectImageTelemetryRecord : BaseDetectionTelemetryRe
public string BaseImageDigest { get; set; }
public string BaseImageRef { get; set; }
-
+
public string ImageInspectResponse { get; set; }
public string ExceptionMessage { get; set; }
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs
index 4e8e163e7..aa566e103 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceSystemInfoTelemetryRecord.cs
@@ -3,9 +3,9 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records
public class DockerServiceSystemInfoTelemetryRecord : BaseDetectionTelemetryRecord
{
public override string RecordName => "DockerServiceSystemInfo";
-
+
public string SystemInfo { get; set; }
-
+
public string ExceptionMessage { get; set; }
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs
index 70bd5d63d..03bb1a44f 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTelemetryRecord.cs
@@ -3,15 +3,15 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records
public class DockerServiceTelemetryRecord : BaseDetectionTelemetryRecord
{
public override string RecordName => "DockerService";
-
+
public string Image { get; set; }
-
+
public string Command { get; set; }
-
+
public string Container { get; set; }
-
+
public string Stdout { get; set; }
-
+
public string Stderr { get; set; }
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs
index c73942482..a1ed32435 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DockerServiceTryPullImageTelemetryRecord.cs
@@ -3,7 +3,7 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records
public class DockerServiceTryPullImageTelemetryRecord : BaseDetectionTelemetryRecord
{
public override string RecordName => "DockerServiceTryPullImage";
-
+
public string Image { get; set; }
public string CreateImageProgress { get; set; }
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs
index 0f811c343..262466b60 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs
@@ -3,11 +3,11 @@
public class LinuxContainerDetectorMissingVersion : BaseDetectionTelemetryRecord
{
public override string RecordName { get; } = "MissingVersion";
-
+
public string Distribution { get; set; }
-
+
public string Release { get; set; }
- public string[] PackageNames { get; set; }
+ public string[] PackageNames { get; set; }
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs
index 706126097..84a859eab 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerSyftTelemetryRecord.cs
@@ -3,7 +3,7 @@ namespace Microsoft.ComponentDetection.Common.Telemetry.Records
public class LinuxScannerSyftTelemetryRecord : BaseDetectionTelemetryRecord
{
public override string RecordName => "LinuxScannerSyftTelemetry";
-
+
public string LinuxComponents { get; set; }
public string Exception { get; set; }
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs
index fef3a5a10..fe8147509 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs
@@ -11,7 +11,7 @@ public class LinuxScannerTelemetryRecord : BaseDetectionTelemetryRecord
public string ScanStdErr { get; set; }
public string FailedDeserializingScannerOutput { get; set; }
-
+
public bool SemaphoreFailure { get; set; }
public string ScannerVersion { get; set; }
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs
index 4f691ca43..3e1f7dc64 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs
@@ -16,20 +16,20 @@ public class NuGetProjectAssetsTelemetryRecord : IDetectionTelemetryRecord, IDis
protected virtual void Dispose(bool disposing)
{
- if (!disposedValue)
+ if (!this.disposedValue)
{
if (disposing)
{
TelemetryRelay.Instance.PostTelemetryRecord(this);
}
- disposedValue = true;
+ this.disposedValue = true;
}
}
public void Dispose()
{
- Dispose(true);
+ this.Dispose(true);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs
index 39ba28e89..4102fc25e 100644
--- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs
+++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs
@@ -1,6 +1,4 @@
-using System.Net;
-
-namespace Microsoft.ComponentDetection.Common.Telemetry.Records
+namespace Microsoft.ComponentDetection.Common.Telemetry.Records
{
public class PypiCacheTelemetryRecord : BaseDetectionTelemetryRecord
{
diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs
index 25866d5e0..8dcae5fa3 100644
--- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs
@@ -29,7 +29,7 @@ public class ContainerDetails
// Summary:
// The digest of the exact image used as the base image
- // This is to avoid errors if there are ref updates between build time and scan time
+ // This is to avoid errors if there are ref updates between build time and scan time
public string BaseImageDigest { get; set; }
// Summary:
diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs
index 4f6774f1f..5c72f728c 100644
--- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs
@@ -1,11 +1,7 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace Microsoft.ComponentDetection.Contracts.BcdeModels
+namespace Microsoft.ComponentDetection.Contracts.BcdeModels
{
- /// Used to communicate Dependency Scope of Component.
- /// Currently only populated for Maven component.
+ /// Used to communicate Dependency Scope of Component.
+ /// Currently only populated for Maven component.
/// The values are ordered in terms of priority, which is used to resolve the scope for duplicate component while merging them.
///
public enum DependencyScope
diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs
index 8dacf105f..1ab815a80 100644
--- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DockerLayer.cs
@@ -1,6 +1,6 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels
{
- public class DockerLayer
+ public class DockerLayer
{
// Summary:
// the command/script that was executed in order to create the layer.
@@ -19,4 +19,4 @@ public class DockerLayer
// Note: only includes non-empty layers
public int LayerIndex { get; set; }
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs
index 760dd725e..cf07bde94 100644
--- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/LayerMappedLinuxComponents.cs
@@ -3,10 +3,10 @@
namespace Microsoft.ComponentDetection.Contracts.BcdeModels
{
- public class LayerMappedLinuxComponents
+ public class LayerMappedLinuxComponents
{
public IEnumerable LinuxComponents { get; set; }
public DockerLayer DockerLayer { get; set; }
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs
index ff3ff79c4..1812bf7f0 100644
--- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Newtonsoft.Json;
@@ -24,6 +24,7 @@ public class TypedComponentConverter : JsonConverter
{ ComponentType.Linux, typeof(LinuxComponent) },
{ ComponentType.Conda, typeof(CondaComponent) },
{ ComponentType.DockerReference, typeof(DockerReferenceComponent) },
+ { ComponentType.Vcpkg, typeof(VcpkgComponent) }
};
public override bool CanConvert(Type objectType)
@@ -35,10 +36,10 @@ public override object ReadJson(
JsonReader reader,
Type objectType, object existingValue, JsonSerializer serializer)
{
- JToken jo = JToken.Load(reader);
+ var jo = JToken.Load(reader);
var value = (ComponentType)Enum.Parse(typeof(ComponentType), (string)jo["type"]);
- var targetType = componentTypesToTypes[value];
+ var targetType = this.componentTypesToTypes[value];
var instanceOfTypedComponent = Activator.CreateInstance(targetType, true);
serializer.Populate(jo.CreateReader(), instanceOfTypedComponent);
diff --git a/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs b/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs
index 8a957614a..a3e8aa0f6 100644
--- a/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs
@@ -17,22 +17,22 @@ public class DetectedComponent
/// Id of the layer the component was found, this is only necessary if the component was found inside a container.
public DetectedComponent(TypedComponent.TypedComponent component, IComponentDetector detector = null, int? containerDetailsId = null, int? containerLayerId = null)
{
- Component = component;
- FilePaths = new HashSet();
- DetectedBy = detector;
- ContainerDetailIds = new HashSet();
- ContainerLayerIds = new Dictionary>();
+ this.Component = component;
+ this.FilePaths = new HashSet();
+ this.DetectedBy = detector;
+ this.ContainerDetailIds = new HashSet();
+ this.ContainerLayerIds = new Dictionary>();
if (containerDetailsId.HasValue)
{
- ContainerDetailIds.Add(containerDetailsId.Value);
+ this.ContainerDetailIds.Add(containerDetailsId.Value);
if (containerLayerId.HasValue)
{
- ContainerLayerIds.Add(containerDetailsId.Value, new List() { containerLayerId.Value });
+ this.ContainerLayerIds.Add(containerDetailsId.Value, new List() { containerLayerId.Value });
}
}
}
- private string DebuggerDisplay => $"{Component.DebuggerDisplay}";
+ private string DebuggerDisplay => $"{this.Component.DebuggerDisplay}";
///
/// Gets or sets the detector that detected this component.
@@ -57,7 +57,7 @@ public DetectedComponent(TypedComponent.TypedComponent component, IComponentDete
/// Gets or sets the layer within a container where this component was found.
public IDictionary> ContainerLayerIds { get; set; }
-
+
/// Gets or sets Dependency Scope of the component.
public DependencyScope? DependencyScope { get; set; }
@@ -65,9 +65,9 @@ public DetectedComponent(TypedComponent.TypedComponent component, IComponentDete
/// The file path to add to the hashset.
public void AddComponentFilePath(string filePath)
{
- lock (hashLock)
+ lock (this.hashLock)
{
- FilePaths.Add(filePath);
+ this.FilePaths.Add(filePath);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs
index 12c995077..7724a52ca 100644
--- a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs
@@ -41,5 +41,8 @@ public enum DetectorClass
/// Indicates a detector applies to Vcpkg packages.
Vcpkg,
+
+ /// Indicates a detector applies to Docker references.
+ DockerReference,
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs b/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs
index b8472bd4e..8728f3556 100644
--- a/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs
@@ -1,11 +1,71 @@
namespace Microsoft.ComponentDetection.Contracts
{
#pragma warning disable SA1402
- public abstract class DockerReference
+ public class DockerReference
{
- public abstract DockerReferenceKind Kind { get; }
+ public virtual DockerReferenceKind Kind { get; }
- public abstract TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent();
+ public virtual TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent()
+ {
+ throw new System.NotImplementedException();
+ }
+
+ public static DockerReference CreateDockerReference(string repository, string domain, string digest, string tag)
+ {
+ if (!string.IsNullOrEmpty(repository) && string.IsNullOrEmpty(domain))
+ {
+ if (!string.IsNullOrEmpty(digest))
+ {
+ return new DigestReference
+ {
+ Digest = digest,
+ };
+ }
+ else
+ {
+ throw new System.InvalidOperationException("Repository name must have at least one component");
+ }
+ }
+ else if (string.IsNullOrEmpty(tag))
+ {
+ if (string.IsNullOrEmpty(digest))
+ {
+ return new CanonicalReference
+ {
+ Domain = domain,
+ Repository = repository,
+ Digest = digest,
+ };
+ }
+ else
+ {
+ return new RepositoryReference
+ {
+ Domain = domain,
+ Repository = repository,
+ };
+ }
+ }
+ else if (string.IsNullOrEmpty(digest))
+ {
+ return new TaggedReference
+ {
+ Domain = domain,
+ Repository = repository,
+ Tag = tag,
+ };
+ }
+ else
+ {
+ return new DualReference
+ {
+ Domain = domain,
+ Repository = repository,
+ Tag = tag,
+ Digest = digest,
+ };
+ }
+ }
}
public enum DockerReferenceKind
@@ -20,11 +80,11 @@ public enum DockerReferenceKind
public class Reference
{
public string Tag { get; set; }
-
+
public string Digest { get; set; }
-
+
public string Repository { get; set; }
-
+
public string Domain { get; set; }
}
@@ -32,19 +92,19 @@ public class Reference
public class DigestReference : DockerReference
{
public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Digest;
-
+
public string Digest;
public override string ToString()
{
- return $"{Digest}";
+ return $"{this.Digest}";
}
public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent()
{
return new TypedComponent.DockerReferenceComponent(this)
{
- Digest = Digest,
+ Digest = this.Digest,
};
}
}
@@ -53,25 +113,25 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo
public class CanonicalReference : DockerReference
{
public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Canonical;
-
+
public string Domain;
-
+
public string Repository;
-
+
public string Digest;
public override string ToString()
{
- return $"{Domain}/{Repository}@${Digest}";
+ return $"{this.Domain}/{this.Repository}@${this.Digest}";
}
public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent()
{
return new TypedComponent.DockerReferenceComponent(this)
{
- Domain = Domain,
- Digest = Digest,
- Name = Repository,
+ Domain = this.Domain,
+ Digest = this.Digest,
+ Repository = this.Repository,
};
}
}
@@ -80,22 +140,22 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo
public class RepositoryReference : DockerReference
{
public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Repository;
-
+
public string Domain;
-
+
public string Repository;
-
+
public override string ToString()
{
- return $"{Repository}";
+ return $"{this.Repository}";
}
public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent()
{
return new TypedComponent.DockerReferenceComponent(this)
{
- Domain = Domain,
- Name = Repository,
+ Domain = this.Domain,
+ Repository = this.Repository,
};
}
}
@@ -104,25 +164,25 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo
public class TaggedReference : DockerReference
{
public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Tagged;
-
+
public string Domain;
-
+
public string Repository;
-
+
public string Tag;
-
+
public override string ToString()
{
- return $"{Domain}/{Repository}:${Tag}";
+ return $"{this.Domain}/{this.Repository}:${this.Tag}";
}
public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent()
{
return new TypedComponent.DockerReferenceComponent(this)
{
- Domain = Domain,
- Tag = Tag,
- Name = Repository,
+ Domain = this.Domain,
+ Tag = this.Tag,
+ Repository = this.Repository,
};
}
}
@@ -131,29 +191,29 @@ public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceCo
public class DualReference : DockerReference
{
public override DockerReferenceKind Kind { get; } = DockerReferenceKind.Dual;
-
+
public string Domain;
-
+
public string Repository;
-
+
public string Tag;
-
+
public string Digest;
public override string ToString()
{
- return $"{Domain}/{Repository}:${Tag}@${Digest}";
+ return $"{this.Domain}/{this.Repository}:${this.Tag}@${this.Digest}";
}
public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent()
{
return new TypedComponent.DockerReferenceComponent(this)
{
- Domain = Domain,
- Digest = Digest,
- Tag = Tag,
- Name = Repository,
+ Domain = this.Domain,
+ Digest = this.Digest,
+ Tag = this.Tag,
+ Repository = this.Repository,
};
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs
index d6428b456..45a13523f 100644
--- a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs
@@ -63,20 +63,20 @@ public abstract class FileComponentDetector : IComponentDetector
///
public async virtual Task ExecuteDetectorAsync(ScanRequest request)
{
- ComponentRecorder = request.ComponentRecorder;
- Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1);
- return await ScanDirectoryAsync(request);
+ this.ComponentRecorder = request.ComponentRecorder;
+ this.Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1);
+ return await this.ScanDirectoryAsync(request);
}
///
private Task ScanDirectoryAsync(ScanRequest request)
{
- CurrentScanRequest = request;
+ this.CurrentScanRequest = request;
- var filteredObservable = Scanner.GetFilteredComponentStreamObservable(request.SourceDirectory, SearchPatterns, request.ComponentRecorder);
+ var filteredObservable = this.Scanner.GetFilteredComponentStreamObservable(request.SourceDirectory, this.SearchPatterns, request.ComponentRecorder);
- Logger?.LogVerbose($"Registered {GetType().FullName}");
- return ProcessAsync(filteredObservable, request.DetectorArgs);
+ this.Logger?.LogVerbose($"Registered {this.GetType().FullName}");
+ return this.ProcessAsync(filteredObservable, request.DetectorArgs);
}
///
@@ -87,14 +87,14 @@ private Task ScanDirectoryAsync(ScanRequest reques
///
protected Task> GetFileStreamsAsync(DirectoryInfo sourceDirectory, ExcludeDirectoryPredicate exclusionPredicate)
{
- return Task.FromResult(ComponentStreamEnumerableFactory.GetComponentStreams(sourceDirectory, SearchPatterns, exclusionPredicate));
+ return Task.FromResult(this.ComponentStreamEnumerableFactory.GetComponentStreams(sourceDirectory, this.SearchPatterns, exclusionPredicate));
}
private async Task ProcessAsync(IObservable processRequests, IDictionary detectorArgs)
{
- var processor = new ActionBlock(async processRequest => await OnFileFound(processRequest, detectorArgs));
+ var processor = new ActionBlock(async processRequest => await this.OnFileFound(processRequest, detectorArgs));
- var preprocessedObserbable = await OnPrepareDetection(processRequests, detectorArgs);
+ var preprocessedObserbable = await this.OnPrepareDetection(processRequests, detectorArgs);
await preprocessedObserbable.ForEachAsync(processRequest => processor.Post(processRequest));
@@ -102,12 +102,12 @@ private async Task ProcessAsync(IObservable
- /// Gets the set of categories this detector is a member of.
+ /// Gets the set of categories this detector is a member of.
/// Names of the enumeration comprise some of the built in categories.
/// If the category "All" is specified, the detector will always run.
///
@@ -44,7 +44,7 @@ public interface IComponentDetector
///
/// Component detectors implementing this interface are, by default, off. This is used during composition to opt detectors out of being on by default.
- /// If opted in, they should behave like a normal detector.
+ /// If opted in, they should behave like a normal detector.
///
public interface IDefaultOffComponentDetector : IComponentDetector
{
diff --git a/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs b/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs
index 49bbe9d87..8dc317935 100644
--- a/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs
@@ -13,7 +13,7 @@ public interface IDetectorDependencies
IFileUtilityService FileUtilityService { get; set; }
IObservableDirectoryWalkerFactory DirectoryWalkerFactory { get; set; }
-
+
IDockerService DockerService { get; set; }
IEnvironmentVariableService EnvironmentVariableService { get; set; }
diff --git a/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs b/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs
index 5c9891a5c..13e1b4e42 100644
--- a/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs
@@ -6,12 +6,12 @@ public class NpmAuthor
{
public NpmAuthor(string name, string email = null)
{
- Name = name ?? throw new ArgumentNullException(nameof(name));
- Email = string.IsNullOrEmpty(email) ? null : email;
+ this.Name = name ?? throw new ArgumentNullException(nameof(name));
+ this.Email = string.IsNullOrEmpty(email) ? null : email;
}
public string Name { get; set; }
-
+
public string Email { get; set; }
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs b/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs
index 62d7fc75c..26108919f 100644
--- a/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/ScanRequest.cs
@@ -15,11 +15,11 @@ public class ScanRequest
/// Detector component recorder.
public ScanRequest(DirectoryInfo sourceDirectory, ExcludeDirectoryPredicate directoryExclusionPredicate, ILogger logger, IDictionary detectorArgs, IEnumerable imagesToScan, IComponentRecorder componentRecorder)
{
- SourceDirectory = sourceDirectory;
- DirectoryExclusionPredicate = directoryExclusionPredicate;
- DetectorArgs = detectorArgs;
- ImagesToScan = imagesToScan;
- ComponentRecorder = componentRecorder;
+ this.SourceDirectory = sourceDirectory;
+ this.DirectoryExclusionPredicate = directoryExclusionPredicate;
+ this.DetectorArgs = detectorArgs;
+ this.ImagesToScan = imagesToScan;
+ this.ComponentRecorder = componentRecorder;
}
/// Gets the source directory to consider the working directory for the detection operation.
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs
index 0859dd0f6..ca196e6b6 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs
@@ -11,8 +11,8 @@ private CargoComponent()
public CargoComponent(string name, string version)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Cargo));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Cargo));
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Cargo));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Cargo));
}
public string Name { get; set; }
@@ -21,8 +21,8 @@ public CargoComponent(string name, string version)
public override ComponentType Type => ComponentType.Cargo;
- public override string Id => $"{Name} {Version} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} - {this.Type}";
- public override PackageURL PackageUrl => new PackageURL("cargo", string.Empty, Name, Version, null, string.Empty);
+ public override PackageURL PackageUrl => new PackageURL("cargo", string.Empty, this.Name, this.Version, null, string.Empty);
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs
index feddfebd1..55637e208 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs
@@ -9,14 +9,14 @@ private CondaComponent()
public CondaComponent(string name, string version, string build, string channel, string subdir, string @namespace, string url, string md5)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Conda));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Conda));
- Build = build;
- Channel = channel;
- Subdir = subdir;
- Namespace = @namespace;
- Url = url;
- MD5 = md5;
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Conda));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Conda));
+ this.Build = build;
+ this.Channel = channel;
+ this.Subdir = subdir;
+ this.Namespace = @namespace;
+ this.Url = url;
+ this.MD5 = md5;
}
public string Build { get; set; }
@@ -37,6 +37,6 @@ public CondaComponent(string name, string version, string build, string channel,
public override ComponentType Type => ComponentType.Conda;
- public override string Id => $"{Name} {Version} {Build} {Channel} {Subdir} {Namespace} {Url} {MD5} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} {this.Build} {this.Channel} {this.Subdir} {this.Namespace} {this.Url} {this.MD5} - {this.Type}";
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs
index 27916aa41..c104665ff 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs
@@ -6,12 +6,12 @@ private DockerImageComponent()
{
/* Reserved for deserialization */
}
-
+
public DockerImageComponent(string hash, string name = null, string tag = null)
{
- Digest = ValidateRequiredInput(hash, nameof(Digest), nameof(ComponentType.DockerImage));
- Name = name;
- Tag = tag;
+ this.Digest = this.ValidateRequiredInput(hash, nameof(this.Digest), nameof(ComponentType.DockerImage));
+ this.Name = name;
+ this.Tag = tag;
}
public string Name { get; set; }
@@ -22,6 +22,6 @@ public DockerImageComponent(string hash, string name = null, string tag = null)
public override ComponentType Type => ComponentType.DockerImage;
- public override string Id => $"{Name} {Tag} {Digest}";
+ public override string Id => $"{this.Name} {this.Tag} {this.Digest}";
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs
index 0c99b229b..5ad27a1ed 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs
@@ -7,19 +7,18 @@ private DockerReferenceComponent()
/* Reserved for deserialization */
}
- public DockerReferenceComponent(string hash, string name = null, string tag = null)
+ public DockerReferenceComponent(string hash, string repository = null, string tag = null)
{
- Digest = ValidateRequiredInput(hash, nameof(Digest), nameof(ComponentType.DockerReference));
- Name = name;
- Tag = tag;
- }
+ this.Digest = this.ValidateRequiredInput(hash, nameof(this.Digest), nameof(ComponentType.DockerReference));
+ this.Repository = repository;
+ this.Tag = tag;
+ }
public DockerReferenceComponent(DockerReference reference)
{
- FullReference = reference;
- }
+ }
- public string Name { get; set; }
+ public string Repository { get; set; }
public string Digest { get; set; }
@@ -29,8 +28,14 @@ public DockerReferenceComponent(DockerReference reference)
public override ComponentType Type => ComponentType.DockerReference;
- public DockerReference FullReference { get; set; }
+ public DockerReference FullReference
+ {
+ get
+ {
+ return DockerReference.CreateDockerReference(this.Repository, this.Domain, this.Digest, this.Tag);
+ }
+ }
- public override string Id => $"{Name} {Tag} {Digest}";
+ public override string Id => $"{this.Repository} {this.Tag} {this.Digest}";
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs
index 0da30ec3e..fd1fb3bfd 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs
@@ -11,14 +11,14 @@ private GitComponent()
public GitComponent(Uri repositoryUrl, string commitHash)
{
- RepositoryUrl = ValidateRequiredInput(repositoryUrl, nameof(RepositoryUrl), nameof(ComponentType.Git));
- CommitHash = ValidateRequiredInput(commitHash, nameof(CommitHash), nameof(ComponentType.Git));
+ this.RepositoryUrl = this.ValidateRequiredInput(repositoryUrl, nameof(this.RepositoryUrl), nameof(ComponentType.Git));
+ this.CommitHash = this.ValidateRequiredInput(commitHash, nameof(this.CommitHash), nameof(ComponentType.Git));
}
public GitComponent(Uri repositoryUrl, string commitHash, string tag)
: this(repositoryUrl, commitHash)
{
- Tag = tag;
+ this.Tag = tag;
}
public Uri RepositoryUrl { get; set; }
@@ -29,6 +29,6 @@ public GitComponent(Uri repositoryUrl, string commitHash, string tag)
public override ComponentType Type => ComponentType.Git;
- public override string Id => $"{RepositoryUrl} : {CommitHash} - {Type}";
+ public override string Id => $"{this.RepositoryUrl} : {this.CommitHash} - {this.Type}";
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs
index d6bb745ba..ad6cca046 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs
@@ -12,16 +12,16 @@ private GoComponent()
public GoComponent(string name, string version)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Go));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Go));
- Hash = string.Empty;
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Go));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Go));
+ this.Hash = string.Empty;
}
public GoComponent(string name, string version, string hash)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Go));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Go));
- Hash = ValidateRequiredInput(hash, nameof(Hash), nameof(ComponentType.Go));
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Go));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Go));
+ this.Hash = this.ValidateRequiredInput(hash, nameof(this.Hash), nameof(ComponentType.Go));
}
public string Name { get; set; }
@@ -32,12 +32,12 @@ public GoComponent(string name, string version, string hash)
public override ComponentType Type => ComponentType.Go;
- public override string Id => $"{Name} {Version} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} - {this.Type}";
public override bool Equals(object other)
{
- GoComponent otherComponent = other as GoComponent;
- return otherComponent != null && Equals(otherComponent);
+ var otherComponent = other as GoComponent;
+ return otherComponent != null && this.Equals(otherComponent);
}
public bool Equals(GoComponent other)
@@ -47,18 +47,16 @@ public bool Equals(GoComponent other)
return false;
}
- return Name == other.Name &&
- Version == other.Version &&
- Hash == other.Hash;
+ return this.Name == other.Name && this.Version == other.Version && this.Hash == other.Hash;
}
public override int GetHashCode()
{
- return Name.GetHashCode() ^ Version.GetHashCode() ^ Hash.GetHashCode();
+ return this.Name.GetHashCode() ^ this.Version.GetHashCode() ^ this.Hash.GetHashCode();
}
// Commit should be used in place of version when available
// https://github.com/package-url/purl-spec/blame/180c46d266c45aa2bd81a2038af3f78e87bb4a25/README.rst#L610
- public override PackageURL PackageUrl => new PackageURL("golang", null, Name, string.IsNullOrWhiteSpace(Hash) ? Version : Hash, null, null);
+ public override PackageURL PackageUrl => new PackageURL("golang", null, this.Name, string.IsNullOrWhiteSpace(this.Hash) ? this.Version : this.Hash, null, null);
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs
index 0b03bb5a3..30f18aaf0 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs
@@ -11,10 +11,10 @@ private LinuxComponent()
public LinuxComponent(string distribution, string release, string name, string version)
{
- Distribution = ValidateRequiredInput(distribution, nameof(Distribution), nameof(ComponentType.Linux));
- Release = ValidateRequiredInput(release, nameof(Release), nameof(ComponentType.Linux));
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Linux));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Linux));
+ this.Distribution = this.ValidateRequiredInput(distribution, nameof(this.Distribution), nameof(ComponentType.Linux));
+ this.Release = this.ValidateRequiredInput(release, nameof(this.Release), nameof(ComponentType.Linux));
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Linux));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Linux));
}
public string Distribution { get; set; }
@@ -27,7 +27,7 @@ public LinuxComponent(string distribution, string release, string name, string v
public override ComponentType Type => ComponentType.Linux;
- public override string Id => $"{Distribution} {Release} {Name} {Version} - {Type}";
+ public override string Id => $"{this.Distribution} {this.Release} {this.Name} {this.Version} - {this.Type}";
public override PackageURL PackageUrl
{
@@ -35,18 +35,18 @@ public override PackageURL PackageUrl
{
string packageType = null;
- if (IsUbuntu() || IsDebian())
+ if (this.IsUbuntu() || this.IsDebian())
{
packageType = "deb";
}
- else if (IsCentOS() || IsFedora() || IsRHEL())
+ else if (this.IsCentOS() || this.IsFedora() || this.IsRHEL())
{
packageType = "rpm";
}
if (packageType != null)
{
- return new PackageURL(packageType, Distribution, Name, Version, null, null);
+ return new PackageURL(packageType, this.Distribution, this.Name, this.Version, null, null);
}
return null;
@@ -55,27 +55,27 @@ public override PackageURL PackageUrl
private bool IsUbuntu()
{
- return Distribution.ToLowerInvariant() == "ubuntu";
+ return this.Distribution.ToLowerInvariant() == "ubuntu";
}
private bool IsDebian()
{
- return Distribution.ToLowerInvariant() == "debian";
+ return this.Distribution.ToLowerInvariant() == "debian";
}
private bool IsCentOS()
{
- return Distribution.ToLowerInvariant() == "centos";
+ return this.Distribution.ToLowerInvariant() == "centos";
}
private bool IsFedora()
{
- return Distribution.ToLowerInvariant() == "fedora";
+ return this.Distribution.ToLowerInvariant() == "fedora";
}
private bool IsRHEL()
{
- return Distribution.ToLowerInvariant() == "red hat enterprise linux";
+ return this.Distribution.ToLowerInvariant() == "red hat enterprise linux";
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs
index b418ead37..a644b052f 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs
@@ -11,9 +11,9 @@ private MavenComponent()
public MavenComponent(string groupId, string artifactId, string version)
{
- GroupId = ValidateRequiredInput(groupId, nameof(GroupId), nameof(ComponentType.Maven));
- ArtifactId = ValidateRequiredInput(artifactId, nameof(ArtifactId), nameof(ComponentType.Maven));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Maven));
+ this.GroupId = this.ValidateRequiredInput(groupId, nameof(this.GroupId), nameof(ComponentType.Maven));
+ this.ArtifactId = this.ValidateRequiredInput(artifactId, nameof(this.ArtifactId), nameof(ComponentType.Maven));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Maven));
}
public string GroupId { get; set; }
@@ -24,8 +24,8 @@ public MavenComponent(string groupId, string artifactId, string version)
public override ComponentType Type => ComponentType.Maven;
- public override string Id => $"{GroupId} {ArtifactId} {Version} - {Type}";
+ public override string Id => $"{this.GroupId} {this.ArtifactId} {this.Version} - {this.Type}";
- public override PackageURL PackageUrl => new PackageURL("maven", GroupId, ArtifactId, Version, null, null);
+ public override PackageURL PackageUrl => new PackageURL("maven", this.GroupId, this.ArtifactId, this.Version, null, null);
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs
index afad4cdf8..c656caebc 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs
@@ -12,10 +12,10 @@ private NpmComponent()
public NpmComponent(string name, string version, string hash = null, NpmAuthor author = null)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Npm));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Npm));
- Hash = hash; // Not required; only found in package-lock.json, not package.json
- Author = author;
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Npm));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Npm));
+ this.Hash = hash; // Not required; only found in package-lock.json, not package.json
+ this.Author = author;
}
public string Name { get; set; }
@@ -28,8 +28,8 @@ public NpmComponent(string name, string version, string hash = null, NpmAuthor a
public override ComponentType Type => ComponentType.Npm;
- public override string Id => $"{Name} {Version} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} - {this.Type}";
- public override PackageURL PackageUrl => new PackageURL("npm", null, Name, Version, null, null);
+ public override PackageURL PackageUrl => new PackageURL("npm", null, this.Name, this.Version, null, null);
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs
index cfbcdf15e..683d95d92 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs
@@ -11,9 +11,9 @@ private NuGetComponent()
public NuGetComponent(string name, string version, string[] authors = null)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.NuGet));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.NuGet));
- Authors = authors;
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.NuGet));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.NuGet));
+ this.Authors = authors;
}
public string Name { get; set; }
@@ -24,8 +24,8 @@ public NuGetComponent(string name, string version, string[] authors = null)
public override ComponentType Type => ComponentType.NuGet;
- public override string Id => $"{Name} {Version} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} - {this.Type}";
- public override PackageURL PackageUrl => new PackageURL("nuget", null, Name, Version, null, null);
+ public override PackageURL PackageUrl => new PackageURL("nuget", null, this.Name, this.Version, null, null);
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs
index 063552227..584cd34b7 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs
@@ -11,10 +11,10 @@ private OtherComponent()
public OtherComponent(string name, string version, Uri downloadUrl, string hash)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Other));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Other));
- DownloadUrl = ValidateRequiredInput(downloadUrl, nameof(DownloadUrl), nameof(ComponentType.Other));
- Hash = hash;
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Other));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Other));
+ this.DownloadUrl = this.ValidateRequiredInput(downloadUrl, nameof(this.DownloadUrl), nameof(ComponentType.Other));
+ this.Hash = hash;
}
public string Name { get; set; }
@@ -27,6 +27,6 @@ public OtherComponent(string name, string version, Uri downloadUrl, string hash)
public override ComponentType Type => ComponentType.Other;
- public override string Id => $"{Name} {Version} {DownloadUrl} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} {this.DownloadUrl} - {this.Type}";
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs
index b11792f17..e83365e2e 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs
@@ -11,8 +11,8 @@ private PipComponent()
public PipComponent(string name, string version)
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Pip));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Pip));
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Pip));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Pip));
}
public string Name { get; set; }
@@ -21,8 +21,8 @@ public PipComponent(string name, string version)
public override ComponentType Type => ComponentType.Pip;
- public override string Id => $"{Name} {Version} - {Type}".ToLowerInvariant();
+ public override string Id => $"{this.Name} {this.Version} - {this.Type}".ToLowerInvariant();
- public override PackageURL PackageUrl => new PackageURL("pypi", null, Name, Version, null, null);
+ public override PackageURL PackageUrl => new PackageURL("pypi", null, this.Name, this.Version, null, null);
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs
index ee958473c..3a2fa8ab4 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs
@@ -12,9 +12,9 @@ private PodComponent()
public PodComponent(string name, string version, string specRepo = "")
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Pod));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Pod));
- SpecRepo = specRepo;
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Pod));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Pod));
+ this.SpecRepo = specRepo;
}
public string Name { get; set; }
@@ -25,19 +25,19 @@ public PodComponent(string name, string version, string specRepo = "")
public override ComponentType Type => ComponentType.Pod;
- public override string Id => $"{Name} {Version} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} - {this.Type}";
public override PackageURL PackageUrl
{
- get
+ get
{
var qualifiers = new SortedDictionary();
- if (!string.IsNullOrWhiteSpace(SpecRepo))
+ if (!string.IsNullOrWhiteSpace(this.SpecRepo))
{
- qualifiers.Add("repository_url", SpecRepo);
+ qualifiers.Add("repository_url", this.SpecRepo);
}
- return new PackageURL("cocoapods", null, Name, Version, qualifiers, null);
+ return new PackageURL("cocoapods", null, this.Name, this.Version, qualifiers, null);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs
index 2b6779a67..130e4acdb 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs
@@ -11,9 +11,9 @@ private RubyGemsComponent()
public RubyGemsComponent(string name, string version, string source = "")
{
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.RubyGems));
- Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.RubyGems));
- Source = source;
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.RubyGems));
+ this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.RubyGems));
+ this.Source = source;
}
public string Name { get; set; }
@@ -24,8 +24,8 @@ public RubyGemsComponent(string name, string version, string source = "")
public override ComponentType Type => ComponentType.RubyGems;
- public override string Id => $"{Name} {Version} - {Type}";
+ public override string Id => $"{this.Name} {this.Version} - {this.Type}";
- public override PackageURL PackageUrl => new PackageURL("gem", null, Name, Version, null, null);
+ public override PackageURL PackageUrl => new PackageURL("gem", null, this.Name, this.Version, null, null);
}
}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs
index 5ec716c5e..1dac70180 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs
@@ -12,13 +12,12 @@ private SpdxComponent()
public SpdxComponent(string spdxVersion, Uri documentNamespace, string name, string checksum,
string rootElementId, string path)
{
- SpdxVersion = ValidateRequiredInput(spdxVersion, nameof(SpdxVersion), nameof(ComponentType.Spdx));
- DocumentNamespace =
- ValidateRequiredInput(documentNamespace, nameof(DocumentNamespace), nameof(ComponentType.Spdx));
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Spdx));
- Checksum = ValidateRequiredInput(checksum, nameof(Checksum), nameof(ComponentType.Spdx));
- RootElementId = ValidateRequiredInput(rootElementId, nameof(RootElementId), nameof(ComponentType.Spdx));
- Path = ValidateRequiredInput(path, nameof(Path), nameof(ComponentType.Spdx));
+ this.SpdxVersion = this.ValidateRequiredInput(spdxVersion, nameof(this.SpdxVersion), nameof(ComponentType.Spdx));
+ this.DocumentNamespace = this.ValidateRequiredInput(documentNamespace, nameof(this.DocumentNamespace), nameof(ComponentType.Spdx));
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Spdx));
+ this.Checksum = this.ValidateRequiredInput(checksum, nameof(this.Checksum), nameof(ComponentType.Spdx));
+ this.RootElementId = this.ValidateRequiredInput(rootElementId, nameof(this.RootElementId), nameof(ComponentType.Spdx));
+ this.Path = this.ValidateRequiredInput(path, nameof(this.Path), nameof(ComponentType.Spdx));
}
public override ComponentType Type => ComponentType.Spdx;
@@ -35,6 +34,6 @@ public SpdxComponent(string spdxVersion, Uri documentNamespace, string name, str
public string Path { get; }
- public override string Id => $"{Name}-{SpdxVersion}-{Checksum}";
+ public override string Id => $"{this.Name}-{this.SpdxVersion}-{this.Checksum}";
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs
index 0bf401458..503ff4591 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs
@@ -28,19 +28,19 @@ internal TypedComponent()
public virtual PackageURL PackageUrl { get; }
[JsonIgnore]
- internal string DebuggerDisplay => $"{Id}";
+ internal string DebuggerDisplay => $"{this.Id}";
protected string ValidateRequiredInput(string input, string fieldName, string componentType)
{
return string.IsNullOrWhiteSpace(input)
- ? throw new ArgumentNullException(fieldName, NullPropertyExceptionMessage(fieldName, componentType))
+ ? throw new ArgumentNullException(fieldName, this.NullPropertyExceptionMessage(fieldName, componentType))
: input;
}
protected T ValidateRequiredInput(T input, string fieldName, string componentType)
{
// Null coalescing for generic types is not available until C# 8
- return EqualityComparer.Default.Equals(input, default(T)) ? throw new ArgumentNullException(fieldName, NullPropertyExceptionMessage(fieldName, componentType)) : input;
+ return EqualityComparer.Default.Equals(input, default(T)) ? throw new ArgumentNullException(fieldName, this.NullPropertyExceptionMessage(fieldName, componentType)) : input;
}
protected string NullPropertyExceptionMessage(string propertyName, string componentType)
diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs
index 41037f922..3765b6632 100644
--- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs
+++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs
@@ -1,4 +1,4 @@
-using PackageUrl;
+using PackageUrl;
namespace Microsoft.ComponentDetection.Contracts.TypedComponent
{
@@ -11,13 +11,15 @@ private VcpkgComponent()
public VcpkgComponent(string spdxid, string name, string version, string triplet = null, string portVersion = null, string description = null, string downloadLocation = null)
{
- SPDXID = ValidateRequiredInput(spdxid, nameof(SPDXID), nameof(ComponentType.Vcpkg));
- Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Vcpkg));
- Version = version;
- PortVersion = portVersion;
- Triplet = triplet;
- Description = description;
- DownloadLocation = downloadLocation;
+ int.TryParse(portVersion, out var port);
+
+ this.SPDXID = this.ValidateRequiredInput(spdxid, nameof(this.SPDXID), nameof(ComponentType.Vcpkg));
+ this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Vcpkg));
+ this.Version = version;
+ this.PortVersion = port;
+ this.Triplet = triplet;
+ this.Description = description;
+ this.DownloadLocation = downloadLocation;
}
public string SPDXID { get; set; }
@@ -32,7 +34,7 @@ public VcpkgComponent(string spdxid, string name, string version, string triplet
public string Description { get; set; }
- public string PortVersion { get; set; }
+ public int PortVersion { get; set; }
public override ComponentType Type => ComponentType.Vcpkg;
@@ -40,13 +42,13 @@ public override string Id
{
get
{
- if (PortVersion != null)
+ if (this.PortVersion > 0)
{
- return $"{Name} {Version}#{PortVersion} - {Type}";
+ return $"{this.Name} {this.Version}#{this.PortVersion} - {this.Type}";
}
else
{
- return $"{Name} {Version} - {Type}";
+ return $"{this.Name} {this.Version} - {this.Type}";
}
}
}
@@ -55,17 +57,17 @@ public override PackageURL PackageUrl
{
get
{
- if (PortVersion != null)
+ if (this.PortVersion > 0)
{
- return new PackageURL($"pkg:vcpkg/{Name}@{Version}?port_version={PortVersion}");
+ return new PackageURL($"pkg:vcpkg/{this.Name}@{this.Version}?port_version={this.PortVersion}");
}
- else if (Version != null)
+ else if (this.Version != null)
{
- return new PackageURL($"pkg:vcpkg/{Name}@{Version}");
+ return new PackageURL($"pkg:vcpkg/{this.Name}@{this.Version}");
}
else
{
- return new PackageURL($"pkg:vcpkg/{Name}");
+ return new PackageURL($"pkg:vcpkg/{this.Name}");
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs
index a368ac227..cec5a37c4 100644
--- a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs
@@ -35,9 +35,9 @@ private class Pod : IYamlConvertible
public IList Dependencies { get; set; }
- public string Podspec => Name.Split('/', 2)[0];
+ public string Podspec => this.Name.Split('/', 2)[0];
- public bool IsSubspec => Name != Podspec;
+ public bool IsSubspec => this.Name != this.Podspec;
public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer)
{
@@ -49,18 +49,18 @@ public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObj
var podInfo = parser.Consume();
var components = podInfo.Value.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
- Name = components[0].Trim();
- Version = components[1].Trim();
+ this.Name = components[0].Trim();
+ this.Version = components[1].Trim();
if (hasDependencies)
{
- Dependencies = (IList)nestedObjectDeserializer(typeof(IList));
+ this.Dependencies = (IList)nestedObjectDeserializer(typeof(IList));
parser.Consume();
}
else
{
- Dependencies = Array.Empty();
+ this.Dependencies = Array.Empty();
}
}
@@ -76,16 +76,16 @@ private class PodDependency : IYamlConvertible
public string PodVersion { get; set; }
- public string Podspec => PodName.Split('/', 2)[0];
+ public string Podspec => this.PodName.Split('/', 2)[0];
- public bool IsSubspec => PodName != Podspec;
+ public bool IsSubspec => this.PodName != this.Podspec;
public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer)
{
var scalar = parser.Consume();
var components = scalar.Value.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
- PodName = components[0].Trim();
- PodVersion = components.Length > 1 ? components[1].Trim() : null;
+ this.PodName = components[0].Trim();
+ this.PodVersion = components.Length > 1 ? components[1].Trim() : null;
}
public void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
@@ -122,17 +122,17 @@ private class PodfileLock
public PodfileLock()
{
- Dependencies = Array.Empty();
- PodspecRepositories = new Dictionary>();
- PodspecChecksums = new Dictionary();
- ExternalSources = new Dictionary>();
- CheckoutOptions = new Dictionary>();
- Pods = Array.Empty();
+ this.Dependencies = Array.Empty();
+ this.PodspecRepositories = new Dictionary>();
+ this.PodspecChecksums = new Dictionary();
+ this.ExternalSources = new Dictionary>();
+ this.CheckoutOptions = new Dictionary>();
+ this.Pods = Array.Empty();
}
public string GetSpecRepositoryOfSpec(string specName)
{
- foreach (var repository in PodspecRepositories)
+ foreach (var repository in this.PodspecRepositories)
{
if (repository.Value.Contains(specName))
{
@@ -159,17 +159,17 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;
- Logger.LogVerbose($"Found {file.Pattern}: {file.Location}");
+ this.Logger.LogVerbose($"Found {file.Pattern}: {file.Location}");
try
{
var podfileLock = await ParsePodfileLock(file);
- ProcessPodfileLock(singleFileComponentRecorder, podfileLock);
+ this.ProcessPodfileLock(singleFileComponentRecorder, podfileLock);
}
catch (Exception e)
{
- Logger.LogFailedReadingFile(file.Location, e);
+ this.Logger.LogFailedReadingFile(file.Location, e);
}
}
@@ -205,7 +205,7 @@ private void ProcessPodfileLock(
// Check if the pod is a root component and add it to the list of discovered components
if (rootPodspecs.Contains(pod.Podspec))
{
- if (nonRootComponents.TryGetValue(key, out DetectedComponent existingComponent))
+ if (nonRootComponents.TryGetValue(key, out var existingComponent))
{
rootComponents.TryAdd(key, existingComponent);
nonRootComponents.Remove(key);
@@ -241,9 +241,9 @@ private void ProcessPodfileLock(
// Check if the Podspec comes from a git repository or not
TypedComponent typedComponent;
string key;
- if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out IDictionary checkoutOptions)
- && checkoutOptions.TryGetValue(":git", out string gitOption)
- && checkoutOptions.TryGetValue(":commit", out string commitOption))
+ if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out var checkoutOptions)
+ && checkoutOptions.TryGetValue(":git", out var gitOption)
+ && checkoutOptions.TryGetValue(":commit", out var commitOption))
{
// Create the Git component
gitOption = NormalizePodfileGitUri(gitOption);
@@ -265,7 +265,7 @@ private void ProcessPodfileLock(
// Check if the pod is a root component and add it to the list of discovered components
if (rootPodspecs.Contains(pod.Podspec))
{
- if (nonRootComponents.TryGetValue(key, out DetectedComponent existingComponent))
+ if (nonRootComponents.TryGetValue(key, out var existingComponent))
{
rootComponents.TryAdd(key, existingComponent);
nonRootComponents.Remove(key);
@@ -284,7 +284,7 @@ private void ProcessPodfileLock(
podSpecs.TryAdd(pod.Podspec, key);
// Update the pod dependencies map
- if (podDependencies.TryGetValue(key, out List dependencies))
+ if (podDependencies.TryGetValue(key, out var dependencies))
{
dependencies.AddRange(pod.Dependencies);
}
@@ -301,7 +301,7 @@ private void ProcessPodfileLock(
foreach (var dependency in pod.Value)
{
- if (podSpecs.TryGetValue(dependency.Podspec, out string dependencyKey))
+ if (podSpecs.TryGetValue(dependency.Podspec, out var dependencyKey))
{
if (dependencyKey != pod.Key)
{
@@ -311,7 +311,7 @@ private void ProcessPodfileLock(
}
else
{
- Logger.LogWarning($"Missing podspec declaration. podspec={dependency.Podspec}, version={dependency.PodVersion}");
+ this.Logger.LogWarning($"Missing podspec declaration. podspec={dependency.Podspec}, version={dependency.PodVersion}");
}
}
}
@@ -335,7 +335,7 @@ private void ProcessPodfileLock(
{
var dependency = dependencies.Dequeue();
- if (rootComponents.TryGetValue(dependency, out DetectedComponent detectedRootComponent))
+ if (rootComponents.TryGetValue(dependency, out var detectedRootComponent))
{
// Found another root component
singleFileComponentRecorder.RegisterUsage(
@@ -343,7 +343,7 @@ private void ProcessPodfileLock(
isExplicitReferencedDependency: true,
parentComponentId: rootComponent.Value.Component.Id);
}
- else if (nonRootComponents.TryGetValue(dependency, out DetectedComponent detectedComponent))
+ else if (nonRootComponents.TryGetValue(dependency, out var detectedComponent))
{
singleFileComponentRecorder.RegisterUsage(
detectedComponent,
@@ -351,7 +351,7 @@ private void ProcessPodfileLock(
parentComponentId: rootComponent.Value.Component.Id);
// Add the new dependecies to the queue
- if (dependenciesMap.TryGetValue(dependency, out HashSet newDependencies))
+ if (dependenciesMap.TryGetValue(dependency, out var newDependencies))
{
newDependencies.ToList().ForEach(dependencies.Enqueue);
}
@@ -385,9 +385,9 @@ private static (Pod pod, string key, DetectedComponent detectedComponent)[] Read
// Check if the Podspec comes from a git repository or not
TypedComponent typedComponent;
string key;
- if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out IDictionary checkoutOptions)
- && checkoutOptions.TryGetValue(":git", out string gitOption)
- && checkoutOptions.TryGetValue(":commit", out string commitOption))
+ if (podfileLock.CheckoutOptions.TryGetValue(pod.Podspec, out var checkoutOptions)
+ && checkoutOptions.TryGetValue(":git", out var gitOption)
+ && checkoutOptions.TryGetValue(":commit", out var commitOption))
{
// Create the Git component
gitOption = NormalizePodfileGitUri(gitOption);
diff --git a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs
index f13691d14..7818e4dc5 100644
--- a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs
@@ -14,7 +14,7 @@
namespace Microsoft.ComponentDetection.Detectors.Dockerfile
{
[Export(typeof(IComponentDetector))]
- public class DockerfileComponentDetector : FileComponentDetector
+ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffComponentDetector
{
[Import]
public ICommandLineInvocationService CommandLineInvocationService { get; set; }
@@ -22,9 +22,9 @@ public class DockerfileComponentDetector : FileComponentDetector
[Import]
public IEnvironmentVariableService EnvVarService { get; set; }
- public override string Id { get; } = "Docker Reference";
+ public override string Id { get; } = "DockerReference";
- public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod) };
+ public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.DockerReference) };
public override IList SearchPatterns { get; } = new List { "dockerfile", "dockerfile.*", "*.dockerfile" };
@@ -39,7 +39,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;
var filePath = file.Location;
- Logger.LogInfo($"Discovered dockerfile: {file.Location}");
+ this.Logger.LogInfo($"Discovered dockerfile: {file.Location}");
string contents;
using (var reader = new StreamReader(file.Stream))
@@ -48,7 +48,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
}
var stageNameMap = new Dictionary();
- var dockerFileComponent = ParseDockerFile(contents, file.Location, singleFileComponentRecorder, stageNameMap);
+ var dockerFileComponent = this.ParseDockerFile(contents, file.Location, singleFileComponentRecorder, stageNameMap);
}
private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary stageNameMap)
@@ -57,7 +57,7 @@ private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFi
var instructions = dockerfileModel.Items;
foreach (var instruction in instructions)
{
- var imageReference = ProcessDockerfileConstruct(instruction, dockerfileModel.EscapeChar, stageNameMap);
+ var imageReference = this.ProcessDockerfileConstruct(instruction, dockerfileModel.EscapeChar, stageNameMap);
if (imageReference != null)
{
singleFileComponentRecorder.RegisterUsage(new DetectedComponent(imageReference.ToTypedDockerReferenceComponent()));
@@ -69,33 +69,41 @@ private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFi
private DockerReference ProcessDockerfileConstruct(DockerfileConstruct construct, char escapeChar, Dictionary stageNameMap)
{
- var instructionKeyword = construct.Type;
- DockerReference baseImage = null;
- if (instructionKeyword == ConstructType.Instruction)
- {
- var constructType = construct.GetType().Name;
- switch (constructType)
+ try
+ {
+ var instructionKeyword = construct.Type;
+ DockerReference baseImage = null;
+ if (instructionKeyword == ConstructType.Instruction)
{
- case "FromInstruction":
- baseImage = ParseFromInstruction(construct, escapeChar, stageNameMap);
- break;
- case "CopyInstruction":
- baseImage = ParseCopyInstruction(construct, escapeChar, stageNameMap);
- break;
- default:
- break;
+ var constructType = construct.GetType().Name;
+ switch (constructType)
+ {
+ case "FromInstruction":
+ baseImage = this.ParseFromInstruction(construct, escapeChar, stageNameMap);
+ break;
+ case "CopyInstruction":
+ baseImage = this.ParseCopyInstruction(construct, escapeChar, stageNameMap);
+ break;
+ default:
+ break;
+ }
}
- }
- return baseImage;
+ return baseImage;
+ } catch (Exception e)
+ {
+ this.Logger.LogError($"Failed to detect a DockerReference component, the component will not be registered. \n Error Message: <{e.Message}>");
+ this.Logger.LogException(e, isError: true, printException: true);
+ return null;
+ }
}
private DockerReference ParseFromInstruction(DockerfileConstruct construct, char escapeChar, Dictionary stageNameMap)
{
var tokens = construct.Tokens.ToArray();
var resolvedFromStatement = construct.ResolveVariables(escapeChar).TrimEnd();
- var fromInstruction = (Valleysoft.DockerfileModel.FromInstruction)construct;
- string reference = fromInstruction.ImageName;
+ var fromInstruction = (FromInstruction)construct;
+ var reference = fromInstruction.ImageName;
if (string.IsNullOrWhiteSpace(resolvedFromStatement) || string.IsNullOrEmpty(reference))
{
return null;
@@ -118,7 +126,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char
if (!string.IsNullOrEmpty(stageNameReference))
{
- if (HasUnresolvedVariables(stageNameReference))
+ if (this.HasUnresolvedVariables(stageNameReference))
{
return null;
}
@@ -126,7 +134,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char
return DockerReferenceUtility.ParseFamiliarName(stageNameReference);
}
- if (HasUnresolvedVariables(reference))
+ if (this.HasUnresolvedVariables(reference))
{
return null;
}
@@ -137,7 +145,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char
private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char escapeChar, Dictionary stageNameMap)
{
var resolvedCopyStatement = construct.ResolveVariables(escapeChar).TrimEnd();
- var copyInstruction = (Valleysoft.DockerfileModel.CopyInstruction)construct;
+ var copyInstruction = (CopyInstruction)construct;
var reference = copyInstruction.FromStageName;
if (string.IsNullOrWhiteSpace(resolvedCopyStatement) || string.IsNullOrWhiteSpace(reference))
{
@@ -147,7 +155,7 @@ private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char
stageNameMap.TryGetValue(reference, out var stageNameReference);
if (!string.IsNullOrEmpty(stageNameReference))
{
- if (HasUnresolvedVariables(stageNameReference))
+ if (this.HasUnresolvedVariables(stageNameReference))
{
return null;
}
@@ -157,7 +165,7 @@ private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char
}
}
- if (HasUnresolvedVariables(reference))
+ if (this.HasUnresolvedVariables(reference))
{
return null;
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs
index 705216a91..f475d3658 100644
--- a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs
@@ -3,7 +3,6 @@
using System.Composition;
using System.IO;
using System.Linq;
-using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
@@ -45,7 +44,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
var file = processRequest.ComponentStream;
var projectRootDirectory = Directory.GetParent(file.Location);
- if (projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path)))
+ if (this.projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path)))
{
return;
}
@@ -53,26 +52,26 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
var wasGoCliScanSuccessful = false;
try
{
- if (!IsGoCliManuallyDisabled())
+ if (!this.IsGoCliManuallyDisabled())
{
- wasGoCliScanSuccessful = await UseGoCliToScan(file.Location, singleFileComponentRecorder);
+ wasGoCliScanSuccessful = await this.UseGoCliToScan(file.Location, singleFileComponentRecorder);
}
else
{
- Logger.LogInfo("Go cli scan was manually disabled, fallback strategy performed." +
- " More info: https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy");
+ this.Logger.LogInfo("Go cli scan was manually disabled, fallback strategy performed." +
+ " More info: https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy");
}
}
catch (Exception ex)
{
- Logger.LogError($"Failed to detect components using go cli. Location: {file.Location}");
- Logger.LogException(ex, isError: true, printException: true);
+ this.Logger.LogError($"Failed to detect components using go cli. Location: {file.Location}");
+ this.Logger.LogException(ex, isError: true, printException: true);
}
finally
{
if (wasGoCliScanSuccessful)
{
- projectRoots.Add(projectRootDirectory.FullName);
+ this.projectRoots.Add(projectRootDirectory.FullName);
}
else
{
@@ -81,15 +80,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
{
case ".mod":
{
- Logger.LogVerbose("Found Go.mod: " + file.Location);
- ParseGoModFile(singleFileComponentRecorder, file);
+ this.Logger.LogVerbose("Found Go.mod: " + file.Location);
+ this.ParseGoModFile(singleFileComponentRecorder, file);
break;
}
case ".sum":
{
- Logger.LogVerbose("Found Go.sum: " + file.Location);
- ParseGoSumFile(singleFileComponentRecorder, file);
+ this.Logger.LogVerbose("Found Go.sum: " + file.Location);
+ this.ParseGoSumFile(singleFileComponentRecorder, file);
break;
}
@@ -110,32 +109,32 @@ private async Task UseGoCliToScan(string location, ISingleFileComponentRec
var projectRootDirectory = Directory.GetParent(location);
record.ProjectRoot = projectRootDirectory.FullName;
- var isGoAvailable = await CommandLineInvocationService.CanCommandBeLocated("go", null, workingDirectory: projectRootDirectory, new[] { "version" });
+ var isGoAvailable = await this.CommandLineInvocationService.CanCommandBeLocated("go", null, workingDirectory: projectRootDirectory, new[] { "version" });
record.IsGoAvailable = isGoAvailable;
if (!isGoAvailable)
{
- Logger.LogInfo("Go CLI was not found in the system");
+ this.Logger.LogInfo("Go CLI was not found in the system");
return false;
}
- Logger.LogInfo("Go CLI was found in system and will be used to generate dependency graph. " +
- "Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " +
- "But, it will introduce noise into the detected components.");
- var goDependenciesProcess = await CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-m", "-json", "all" });
+ this.Logger.LogInfo("Go CLI was found in system and will be used to generate dependency graph. " +
+ "Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " +
+ "But, it will introduce noise into the detected components.");
+ var goDependenciesProcess = await this.CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-m", "-json", "all" });
if (goDependenciesProcess.ExitCode != 0)
{
- Logger.LogError($"Go CLI command \"go list -m -json all\" failed with error:\n {goDependenciesProcess.StdErr}");
- Logger.LogError($"Go CLI could not get dependency build list at location: {location}. Fallback go.sum/go.mod parsing will be used.");
+ this.Logger.LogError($"Go CLI command \"go list -m -json all\" failed with error:\n {goDependenciesProcess.StdErr}");
+ this.Logger.LogError($"Go CLI could not get dependency build list at location: {location}. Fallback go.sum/go.mod parsing will be used.");
return false;
}
- RecordBuildDependencies(goDependenciesProcess.StdOut, singleFileComponentRecorder);
+ this.RecordBuildDependencies(goDependenciesProcess.StdOut, singleFileComponentRecorder);
- var generateGraphProcess = await CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new List { "mod", "graph" }.ToArray());
+ var generateGraphProcess = await this.CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new List { "mod", "graph" }.ToArray());
if (generateGraphProcess.ExitCode == 0)
{
- PopulateDependencyGraph(generateGraphProcess.StdOut, singleFileComponentRecorder);
+ this.PopulateDependencyGraph(generateGraphProcess.StdOut, singleFileComponentRecorder);
record.WasGraphSuccessful = true;
}
@@ -148,7 +147,7 @@ private void ParseGoModFile(
{
using var reader = new StreamReader(file.Stream);
- string line = reader.ReadLine();
+ var line = reader.ReadLine();
while (line != null && !line.StartsWith("require ("))
{
line = reader.ReadLine();
@@ -157,13 +156,13 @@ private void ParseGoModFile(
// Stopping at the first ) restrict the detection to only the require section.
while ((line = reader.ReadLine()) != null && !line.EndsWith(")"))
{
- if (TryToCreateGoComponentFromModLine(line, out var goComponent))
+ if (this.TryToCreateGoComponentFromModLine(line, out var goComponent))
{
singleFileComponentRecorder.RegisterUsage(new DetectedComponent(goComponent));
}
else
{
- Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]");
+ this.Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]");
}
}
}
@@ -185,8 +184,8 @@ private bool TryToCreateGoComponentFromModLine(string line, out GoComponent goCo
return true;
}
- //For more information about the format of the go.sum file
- //visit https://golang.org/cmd/go/#hdr-Module_authentication_using_go_sum
+ // For more information about the format of the go.sum file
+ // visit https://golang.org/cmd/go/#hdr-Module_authentication_using_go_sum
private void ParseGoSumFile(
ISingleFileComponentRecorder singleFileComponentRecorder,
IComponentStream file)
@@ -196,20 +195,20 @@ private void ParseGoSumFile(
string line;
while ((line = reader.ReadLine()) != null)
{
- if (TryToCreateGoComponentFromSumLine(line, out var goComponent))
+ if (this.TryToCreateGoComponentFromSumLine(line, out var goComponent))
{
singleFileComponentRecorder.RegisterUsage(new DetectedComponent(goComponent));
}
else
{
- Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]");
+ this.Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]");
}
}
}
private bool TryToCreateGoComponentFromSumLine(string line, out GoComponent goComponent)
{
- Match m = GoSumRegex.Match(line);
+ var m = GoSumRegex.Match(line);
if (m.Success)
{
goComponent = new GoComponent(m.Groups["name"].Value, m.Groups["version"].Value, m.Groups["hash"].Value);
@@ -239,16 +238,16 @@ private void PopulateDependencyGraph(string goGraphOutput, ISingleFileComponentR
continue;
}
- Logger.LogWarning("Unexpected relationship output from go mod graph:");
- Logger.LogWarning(relationship);
+ this.Logger.LogWarning("Unexpected relationship output from go mod graph:");
+ this.Logger.LogWarning(relationship);
continue;
}
GoComponent parentComponent;
GoComponent childComponent;
- var isParentParsed = TryCreateGoComponentFromRelationshipPart(components[0], out parentComponent);
- var isChildParsed = TryCreateGoComponentFromRelationshipPart(components[1], out childComponent);
+ var isParentParsed = this.TryCreateGoComponentFromRelationshipPart(components[0], out parentComponent);
+ var isChildParsed = this.TryCreateGoComponentFromRelationshipPart(components[1], out childComponent);
if (!isParentParsed)
{
@@ -258,14 +257,14 @@ private void PopulateDependencyGraph(string goGraphOutput, ISingleFileComponentR
if (isChildParsed)
{
- if (IsModuleInBuildList(componentRecorder, parentComponent) && IsModuleInBuildList(componentRecorder, childComponent))
+ if (this.IsModuleInBuildList(componentRecorder, parentComponent) && this.IsModuleInBuildList(componentRecorder, childComponent))
{
componentRecorder.RegisterUsage(new DetectedComponent(childComponent), parentComponentId: parentComponent.Id);
}
}
else
{
- Logger.LogWarning($"Failed to parse components from relationship string {relationship}");
+ this.Logger.LogWarning($"Failed to parse components from relationship string {relationship}");
}
}
}
@@ -325,7 +324,7 @@ private bool TryCreateGoComponentFromRelationshipPart(string relationship, out G
private bool IsGoCliManuallyDisabled()
{
- return EnvVarService.IsEnvironmentVariableValueTrue("DisableGoCliScan");
+ return this.EnvVarService.IsEnvironmentVariableValueTrue("DisableGoCliScan");
}
private class GoBuildModule
diff --git a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs
index 873f4eba1..0382b0a8a 100644
--- a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs
@@ -31,8 +31,8 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs)
{
- if (await IsAntLocallyAvailableAsync())
+ if (await this.IsAntLocallyAvailableAsync())
{
return processRequests;
}
- Logger.LogVerbose("Skipping Ivy detection as ant is not available in the local PATH.");
+ this.Logger.LogVerbose("Skipping Ivy detection as ant is not available in the local PATH.");
return Enumerable.Empty().ToObservable();
}
@@ -80,18 +80,18 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
{
if (File.Exists(ivySettingsFilePath))
{
- Logger.LogInfo($"Processing {ivyXmlFile.Location} and ivysettings.xml.");
- await ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, ivySettingsFilePath);
+ this.Logger.LogInfo($"Processing {ivyXmlFile.Location} and ivysettings.xml.");
+ await this.ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, ivySettingsFilePath);
}
else
{
- Logger.LogInfo($"Processing {ivyXmlFile.Location}.");
- await ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, null);
+ this.Logger.LogInfo($"Processing {ivyXmlFile.Location}.");
+ await this.ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, null);
}
}
else
{
- Logger.LogError($"File {ivyXmlFile.Location} passed to OnFileFound, but does not exist!");
+ this.Logger.LogError($"File {ivyXmlFile.Location} passed to OnFileFound, but does not exist!");
}
}
@@ -102,28 +102,28 @@ private async Task ProcessIvyAndIvySettingsFilesAsync(
{
try
{
- string workingDirectory = Path.Combine(Path.GetTempPath(), "ComponentDetection_Ivy");
- Logger.LogVerbose($"Preparing temporary Ivy project in {workingDirectory}");
+ var workingDirectory = Path.Combine(Path.GetTempPath(), "ComponentDetection_Ivy");
+ this.Logger.LogVerbose($"Preparing temporary Ivy project in {workingDirectory}");
if (Directory.Exists(workingDirectory))
{
Directory.Delete(workingDirectory, recursive: true);
}
- InitTemporaryAntProject(workingDirectory, ivyXmlFile, ivySettingsXmlFile);
- if (await RunAntToDetectDependenciesAsync(workingDirectory))
+ this.InitTemporaryAntProject(workingDirectory, ivyXmlFile, ivySettingsXmlFile);
+ if (await this.RunAntToDetectDependenciesAsync(workingDirectory))
{
- string instructionsFile = Path.Combine(workingDirectory, "target", "RegisterUsage.json");
- RegisterUsagesFromFile(singleFileComponentRecorder, instructionsFile);
+ var instructionsFile = Path.Combine(workingDirectory, "target", "RegisterUsage.json");
+ this.RegisterUsagesFromFile(singleFileComponentRecorder, instructionsFile);
}
Directory.Delete(workingDirectory, recursive: true);
}
catch (Exception e)
{
- Logger.LogError("Exception occurred during Ivy file processing: " + e);
+ this.Logger.LogError("Exception occurred during Ivy file processing: " + e);
// If something went wrong, just ignore the file
- Logger.LogFailedReadingFile(ivyXmlFile, e);
+ this.Logger.LogFailedReadingFile(ivyXmlFile, e);
}
}
@@ -138,15 +138,15 @@ private void InitTemporaryAntProject(string workingDirectory, string ivyXmlFile,
var assembly = Assembly.GetExecutingAssembly();
- using (Stream fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.build.xml"))
- using (FileStream fileOut = File.Create(Path.Combine(workingDirectory, "build.xml")))
+ using (var fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.build.xml"))
+ using (var fileOut = File.Create(Path.Combine(workingDirectory, "build.xml")))
{
fileIn.CopyTo(fileOut);
}
Directory.CreateDirectory(Path.Combine(workingDirectory, "java-src"));
- using (Stream fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.java_src.IvyComponentDetectionAntTask.java"))
- using (FileStream fileOut = File.Create(Path.Combine(workingDirectory, "java-src", "IvyComponentDetectionAntTask.java")))
+ using (var fileIn = assembly.GetManifestResourceStream("Microsoft.ComponentDetection.Detectors.ivy.Resources.java_src.IvyComponentDetectionAntTask.java"))
+ using (var fileOut = File.Create(Path.Combine(workingDirectory, "java-src", "IvyComponentDetectionAntTask.java")))
{
fileIn.CopyTo(fileOut);
}
@@ -156,40 +156,40 @@ private async Task IsAntLocallyAvailableAsync()
{
// Note: calling CanCommandBeLocated populates a cache of valid commands. If it is not called before ExecuteCommand,
// ExecuteCommand calls CanCommandBeLocated with no arguments, which fails.
- return await CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, AntVersionArgument);
+ return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, AntVersionArgument);
}
private async Task RunAntToDetectDependenciesAsync(string workingDirectory)
{
- bool ret = false;
- Logger.LogVerbose($"Executing command `ant resolve-dependencies` in directory {workingDirectory}");
- CommandLineExecutionResult result = await CommandLineInvocationService.ExecuteCommand(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies");
+ var ret = false;
+ this.Logger.LogVerbose($"Executing command `ant resolve-dependencies` in directory {workingDirectory}");
+ var result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies");
if (result.ExitCode == 0)
{
- Logger.LogVerbose("Ant command succeeded");
+ this.Logger.LogVerbose("Ant command succeeded");
ret = true;
}
else
{
- Logger.LogError($"Ant command failed with return code {result.ExitCode}");
+ this.Logger.LogError($"Ant command failed with return code {result.ExitCode}");
}
if (string.IsNullOrWhiteSpace(result.StdOut))
{
- Logger.LogVerbose("Ant command wrote nothing to stdout.");
+ this.Logger.LogVerbose("Ant command wrote nothing to stdout.");
}
else
{
- Logger.LogVerbose("Ant command stdout:\n" + result.StdOut);
+ this.Logger.LogVerbose("Ant command stdout:\n" + result.StdOut);
}
if (string.IsNullOrWhiteSpace(result.StdErr))
{
- Logger.LogVerbose("Ant command wrote nothing to stderr.");
+ this.Logger.LogVerbose("Ant command wrote nothing to stderr.");
}
else
{
- Logger.LogWarning("Ant command stderr:\n" + result.StdErr);
+ this.Logger.LogWarning("Ant command stderr:\n" + result.StdErr);
}
return ret;
@@ -210,14 +210,14 @@ private static MavenComponent JsonGavToComponent(JToken gav)
private void RegisterUsagesFromFile(ISingleFileComponentRecorder singleFileComponentRecorder, string instructionsFile)
{
- JObject instructionsJson = JObject.Parse(File.ReadAllText(instructionsFile));
- JContainer instructionsList = (JContainer)instructionsJson["RegisterUsage"];
- foreach (JToken dep in instructionsList)
- {
- MavenComponent component = JsonGavToComponent(dep["gav"]);
- bool isDevDependency = dep.Value("DevelopmentDependency");
- MavenComponent parentComponent = JsonGavToComponent(dep["parent_gav"]);
- bool isResolved = dep.Value("resolved");
+ var instructionsJson = JObject.Parse(File.ReadAllText(instructionsFile));
+ var instructionsList = (JContainer)instructionsJson["RegisterUsage"];
+ foreach (var dep in instructionsList)
+ {
+ var component = JsonGavToComponent(dep["gav"]);
+ var isDevDependency = dep.Value("DevelopmentDependency");
+ var parentComponent = JsonGavToComponent(dep["parent_gav"]);
+ var isResolved = dep.Value("resolved");
if (isResolved)
{
singleFileComponentRecorder.RegisterUsage(
@@ -228,7 +228,7 @@ private void RegisterUsagesFromFile(ISingleFileComponentRecorder singleFileCompo
}
else
{
- Logger.LogWarning($"Dependency \"{component.Id}\" could not be resolved by Ivy, and so has not been recorded by Component Detection.");
+ this.Logger.LogWarning($"Dependency \"{component.Id}\" could not be resolved by Ivy, and so has not been recorded by Component Detection.");
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs b/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs
index 69d8fa481..12d715675 100644
--- a/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs
@@ -3,11 +3,12 @@
// Can convert JSON Schema to C# using quicktype.io.
// (change name of top Coordinate class to SyftOutput)
//
-using System;
-using System.Collections.Generic;
namespace Microsoft.ComponentDetection.Detectors.Linux.Contracts
{
+ using System;
+ using System.Collections.Generic;
+
public partial class SyftOutput
{
public Relationship[] ArtifactRelationships { get; set; }
@@ -313,7 +314,7 @@ public partial struct ConfigurationUnion
public static implicit operator ConfigurationUnion(double Double) => new ConfigurationUnion { Double = Double };
public static implicit operator ConfigurationUnion(long Integer) => new ConfigurationUnion { Integer = Integer };
public static implicit operator ConfigurationUnion(string String) => new ConfigurationUnion { String = String };
- public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null;
+ public bool IsNull => this.AnythingArray == null && this.Bool == null && this.Double == null && this.Integer == null && this.AnythingMap == null && this.String == null;
}
public partial struct Author
diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs
index 0ea1393f2..1d19c78ba 100644
--- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs
@@ -46,26 +46,26 @@ public async Task ExecuteDetectorAsync(ScanRequest
if (imagesToProcess == null || !imagesToProcess.Any())
{
- Logger.LogInfo("No instructions received to scan docker images.");
+ this.Logger.LogInfo("No instructions received to scan docker images.");
return EmptySuccessfulScan();
}
var cancellationTokenSource = new CancellationTokenSource(GetTimeout(request.DetectorArgs));
- if (!await DockerService.CanRunLinuxContainersAsync(cancellationTokenSource.Token))
+ if (!await this.DockerService.CanRunLinuxContainersAsync(cancellationTokenSource.Token))
{
using var record = new LinuxContainerDetectorUnsupportedOs
{
Os = RuntimeInformation.OSDescription,
};
- Logger.LogInfo("Linux containers are not available on this host.");
+ this.Logger.LogInfo("Linux containers are not available on this host.");
return EmptySuccessfulScan();
}
var results = Enumerable.Empty();
try
{
- results = await ProcessImagesAsync(imagesToProcess, request.ComponentRecorder, cancellationTokenSource.Token);
+ results = await this.ProcessImagesAsync(imagesToProcess, request.ComponentRecorder, cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
@@ -91,15 +91,15 @@ private async Task> ProcessImagesAsync(
try
{
// Check image exists locally. Try docker pull if not
- if (!(await DockerService.ImageExistsLocallyAsync(image, cancellationToken) ||
- await DockerService.TryPullImageAsync(image, cancellationToken)))
+ if (!(await this.DockerService.ImageExistsLocallyAsync(image, cancellationToken) ||
+ await this.DockerService.TryPullImageAsync(image, cancellationToken)))
{
throw new InvalidUserInputException(
$"Docker image {image} could not be found locally and could not be pulled. Verify the image is either available locally or through docker pull.",
null);
}
- var imageDetails = await DockerService.InspectImageAsync(image, cancellationToken);
+ var imageDetails = await this.DockerService.InspectImageAsync(image, cancellationToken);
// Unable to fetch image details
if (imageDetails == null)
@@ -111,7 +111,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken)))
}
catch (Exception e)
{
- Logger.LogWarning($"Processing of image {image} failed with exception: {e.Message}");
+ this.Logger.LogWarning($"Processing of image {image} failed with exception: {e.Message}");
using var record = new LinuxContainerDetectorImageDetectionFailed
{
ExceptionType = e.GetType().ToString(),
@@ -130,9 +130,9 @@ await DockerService.TryPullImageAsync(image, cancellationToken)))
{
var internalContainerDetails = kvp.Value;
var image = kvp.Key;
- int baseImageLayerCount = await GetBaseImageLayerCount(internalContainerDetails, image, cancellationToken);
+ var baseImageLayerCount = await this.GetBaseImageLayerCount(internalContainerDetails, image, cancellationToken);
- //Update the layer information to specify if a layer was fond in the specified baseImage
+ // Update the layer information to specify if a layer was fond in the specified baseImage
internalContainerDetails.Layers = internalContainerDetails.Layers.Select(layer => new DockerLayer
{
DiffId = layer.DiffId,
@@ -140,7 +140,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken)))
IsBaseImage = layer.LayerIndex < baseImageLayerCount,
});
- var layers = await LinuxScanner.ScanLinuxAsync(kvp.Value.ImageId, internalContainerDetails.Layers, baseImageLayerCount, cancellationToken);
+ var layers = await this.LinuxScanner.ScanLinuxAsync(kvp.Value.ImageId, internalContainerDetails.Layers, baseImageLayerCount, cancellationToken);
var components = layers.SelectMany(layer => layer.LinuxComponents.Select(linuxComponent => new DetectedComponent(linuxComponent, null, internalContainerDetails.Id, layer.DockerLayer.LayerIndex)));
internalContainerDetails.Layers = layers.Select(layer => layer.DockerLayer);
@@ -154,7 +154,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken)))
}
catch (Exception e)
{
- Logger.LogWarning($"Scanning of image {kvp.Key} failed with exception: {e.Message}");
+ this.Logger.LogWarning($"Scanning of image {kvp.Key} failed with exception: {e.Message}");
using var record = new LinuxContainerDetectorImageDetectionFailed
{
ExceptionType = e.GetType().ToString(),
@@ -212,28 +212,32 @@ private async Task GetBaseImageLayerCount(ContainerDetails scannedImageDeta
if (string.IsNullOrEmpty(scannedImageDetails.BaseImageRef))
{
record.BaseImageLayerMessage = $"Base image annotations not found on image {image}, Results will not be mapped to base image layers";
- Logger.LogInfo(record.BaseImageLayerMessage);
+ this.Logger.LogInfo(record.BaseImageLayerMessage);
+ return 0;
+ } else if (scannedImageDetails.BaseImageRef == "scratch") {
+ record.BaseImageLayerMessage = $"{image} has no base image";
+ this.Logger.LogInfo(record.BaseImageLayerMessage);
return 0;
}
var baseImageDigest = scannedImageDetails.BaseImageDigest;
- var refWithDigest = scannedImageDetails.BaseImageRef + (baseImageDigest != string.Empty ? $"@{baseImageDigest}" : string.Empty);
+ var refWithDigest = scannedImageDetails.BaseImageRef + (!string.IsNullOrEmpty(baseImageDigest) ? $"@{baseImageDigest}" : string.Empty);
record.BaseImageDigest = baseImageDigest;
record.BaseImageRef = scannedImageDetails.BaseImageRef;
- if (!(await DockerService.ImageExistsLocallyAsync(refWithDigest, cancellationToken) ||
- await DockerService.TryPullImageAsync(refWithDigest, cancellationToken)))
+ if (!(await this.DockerService.ImageExistsLocallyAsync(refWithDigest, cancellationToken) ||
+ await this.DockerService.TryPullImageAsync(refWithDigest, cancellationToken)))
{
record.BaseImageLayerMessage = $"Base image {refWithDigest} could not be found locally and could not be pulled. Results will not be mapped to base image layers";
- Logger.LogInfo(record.BaseImageLayerMessage);
+ this.Logger.LogInfo(record.BaseImageLayerMessage);
return 0;
}
- var baseImageDetails = await DockerService.InspectImageAsync(refWithDigest, cancellationToken);
- if (!ValidateBaseImageLayers(scannedImageDetails, baseImageDetails))
+ var baseImageDetails = await this.DockerService.InspectImageAsync(refWithDigest, cancellationToken);
+ if (!this.ValidateBaseImageLayers(scannedImageDetails, baseImageDetails))
{
record.BaseImageLayerMessage = $"Docker image {image} was set to have base image {refWithDigest} but is not built off of it. Results will not be mapped to base image layers";
- Logger.LogInfo(record.BaseImageLayerMessage);
+ this.Logger.LogInfo(record.BaseImageLayerMessage);
return 0;
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs
index 5b3ba1493..b48381162 100644
--- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs
@@ -17,7 +17,7 @@ namespace Microsoft.ComponentDetection.Detectors.Linux
[Export(typeof(ILinuxScanner))]
public class LinuxScanner : ILinuxScanner
{
- private const string ScannerImage = "governancecontainerregistry.azurecr.io/syft:0.49.0@sha256:6c2e6bdffa548140b71db87dba9353099cb58103fcd532ab3d68c495248e5adf";
+ private const string ScannerImage = "governancecontainerregistry.azurecr.io/syft:v0.53.4@sha256:04ed9c717a814fdccf52758b67333632a0ff16840fc393f5fba5864285eaebbe";
private static readonly IList CmdParameters = new List
{
@@ -58,19 +58,19 @@ public async Task> ScanLinuxAsync(string
try
{
var command = new List { imageHash }.Concat(CmdParameters).ToList();
- (stdout, stderr) = await DockerService.CreateAndRunContainerAsync(ScannerImage, command, cancellationToken);
+ (stdout, stderr) = await this.DockerService.CreateAndRunContainerAsync(ScannerImage, command, cancellationToken);
}
catch (Exception e)
{
syftTelemetryRecord.Exception = JsonConvert.SerializeObject(e);
- Logger.LogException(e, false);
+ this.Logger.LogException(e, false);
throw;
}
}
else
{
record.SemaphoreFailure = true;
- Logger.LogWarning($"Failed to enter the docker semaphore for image {imageHash}");
+ this.Logger.LogWarning($"Failed to enter the docker semaphore for image {imageHash}");
}
}
finally
diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs
index 679ae7e48..c4ad7fc0d 100644
--- a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs
@@ -10,7 +10,7 @@ public class GraphNode
{
public GraphNode(T value)
{
- Value = value;
+ this.Value = value;
}
public T Value { get; set; }
diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs
index 01ed2656f..cbf479e41 100644
--- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs
@@ -29,27 +29,27 @@ public class MavenCommandService : IMavenCommandService
public async Task MavenCLIExists()
{
- return await CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument);
+ return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument);
}
public async Task GenerateDependenciesFile(ProcessRequest processRequest)
{
var pomFile = processRequest.ComponentStream;
- var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={BcdeMvnDependencyFileName}", "-DoutputType=text", $"-f{pomFile.Location}" };
- var result = await CommandLineInvocationService.ExecuteCommand(PrimaryCommand, AdditionalValidCommands, cliParameters);
+ var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={this.BcdeMvnDependencyFileName}", "-DoutputType=text", $"-f{pomFile.Location}" };
+ var result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, AdditionalValidCommands, cliParameters);
if (result.ExitCode != 0)
{
- Logger.LogVerbose($"Mvn execution failed for pom file: {pomFile.Location}");
- Logger.LogError(string.IsNullOrEmpty(result.StdErr) ? result.StdOut : result.StdErr);
+ this.Logger.LogVerbose($"Mvn execution failed for pom file: {pomFile.Location}");
+ this.Logger.LogError(string.IsNullOrEmpty(result.StdErr) ? result.StdOut : result.StdErr);
}
}
public void ParseDependenciesFile(ProcessRequest processRequest)
{
- using StreamReader sr = new StreamReader(processRequest.ComponentStream.Stream);
+ using var sr = new StreamReader(processRequest.ComponentStream.Stream);
var lines = sr.ReadToEnd().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
- ParserService.Parse(lines, processRequest.SingleFileComponentRecorder);
+ this.ParserService.Parse(lines, processRequest.SingleFileComponentRecorder);
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs
index 610adc433..b4e95a2b3 100644
--- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Net;
using System.Text.RegularExpressions;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
@@ -10,7 +9,7 @@ namespace Microsoft.ComponentDetection.Detectors.Maven
{
public static class MavenParsingUtilities
{
- private static readonly Dictionary MavenScopeToDependencyScopeMapping = new Dictionary()
+ private static readonly Dictionary MavenScopeToDependencyScopeMapping = new Dictionary()
{
{ "compile", DependencyScope.MavenCompile },
{ "provided", DependencyScope.MavenProvided },
@@ -51,7 +50,7 @@ private static (string groupId, string artifactId, string version, bool? isDevel
}
// 'MavenCompile' is a default scope for maven dependencies.
- DependencyScope dependencyScope = DependencyScope.MavenCompile;
+ var dependencyScope = DependencyScope.MavenCompile;
var groupId = results[0];
var artifactId = results[1];
var version = results[3];
@@ -60,8 +59,8 @@ private static (string groupId, string artifactId, string version, bool? isDevel
{
dependencyScope = MavenScopeToDependencyScopeMapping.TryGetValue(
Regex.Match(results[4], @"^([\w]+)").Value,
- out dependencyScope)
- ? dependencyScope
+ out dependencyScope)
+ ? dependencyScope
: throw new InvalidOperationException($"Invalid scope ('{results[4]}') found for '{mavenComponentString}' found in generated dependency graph.");
isDevDependency = dependencyScope == DependencyScope.MavenTest;
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs
index 8efc18f47..95dfe38a7 100644
--- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs
@@ -21,12 +21,12 @@ public class MavenStyleDependencyGraphParser
private void StartDependencyCategory(string categoryName)
{
- if (DependencyCategory != null)
+ if (this.DependencyCategory != null)
{
throw new InvalidOperationException("Current category must be finished before starting new category.");
}
- DependencyCategory = new GraphNode(categoryName);
+ this.DependencyCategory = new GraphNode(categoryName);
}
public GraphNode Parse(string[] lines)
@@ -34,21 +34,21 @@ public GraphNode Parse(string[] lines)
foreach (var line in lines)
{
var localLine = line.Trim(TrimCharacters);
- if (!string.IsNullOrWhiteSpace(localLine) && DependencyCategory == null)
+ if (!string.IsNullOrWhiteSpace(localLine) && this.DependencyCategory == null)
{
- StartDependencyCategory(localLine);
+ this.StartDependencyCategory(localLine);
}
else
{
var splitterOrDefault = ComponentSplitters.FirstOrDefault(x => localLine.Contains(x));
if (splitterOrDefault != null)
{
- TrackDependency(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim());
+ this.TrackDependency(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim());
}
}
}
- return DependencyCategory;
+ return this.DependencyCategory;
}
public void Parse(string[] lines, ISingleFileComponentRecorder singleFileComponentRecorder)
@@ -56,10 +56,10 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone
foreach (var line in lines)
{
var localLine = line.Trim(TrimCharacters);
- if (!string.IsNullOrWhiteSpace(localLine) && topLevelComponent == null)
+ if (!string.IsNullOrWhiteSpace(localLine) && this.topLevelComponent == null)
{
var topLevelMavenStringInfo = MavenParsingUtilities.GenerateDetectedComponentAndMetadataFromMavenString(localLine);
- topLevelComponent = topLevelMavenStringInfo.Component;
+ this.topLevelComponent = topLevelMavenStringInfo.Component;
singleFileComponentRecorder.RegisterUsage(
topLevelMavenStringInfo.Component,
isDevelopmentDependency: topLevelMavenStringInfo.IsDevelopmentDependency,
@@ -71,7 +71,7 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone
if (splitterOrDefault != null)
{
- RecordDependencies(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim(), singleFileComponentRecorder);
+ this.RecordDependencies(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim(), singleFileComponentRecorder);
}
}
}
@@ -79,40 +79,40 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone
private void TrackDependency(int position, string versionedComponent)
{
- while (stack.Count > 0 && stack.Peek().ParseLevel >= position)
+ while (this.stack.Count > 0 && this.stack.Peek().ParseLevel >= position)
{
- stack.Pop();
+ this.stack.Pop();
}
var myNode = new GraphNodeAtLevel(position, versionedComponent);
- if (stack.Count > 0)
+ if (this.stack.Count > 0)
{
- var parent = stack.Peek();
+ var parent = this.stack.Peek();
parent.Children.Add(myNode);
myNode.Parents.Add(parent);
}
else
{
- DependencyCategory.Children.Add(myNode);
+ this.DependencyCategory.Children.Add(myNode);
}
- stack.Push(myNode);
+ this.stack.Push(myNode);
}
private void RecordDependencies(int position, string versionedComponent, ISingleFileComponentRecorder componentRecorder)
{
- while (tupleStack.Count > 0 && tupleStack.Peek().ParseLevel >= position)
+ while (this.tupleStack.Count > 0 && this.tupleStack.Peek().ParseLevel >= position)
{
- tupleStack.Pop();
+ this.tupleStack.Pop();
}
var componentAndDevDependencyTuple = MavenParsingUtilities.GenerateDetectedComponentAndMetadataFromMavenString(versionedComponent);
var newTuple = (ParseLevel: position, componentAndDevDependencyTuple.Component);
- if (tupleStack.Count > 0)
+ if (this.tupleStack.Count > 0)
{
- var parent = tupleStack.Peek().Component;
+ var parent = this.tupleStack.Peek().Component;
componentRecorder.RegisterUsage(parent);
componentRecorder.RegisterUsage(
newTuple.Component,
@@ -125,12 +125,12 @@ private void RecordDependencies(int position, string versionedComponent, ISingle
componentRecorder.RegisterUsage(
newTuple.Component,
isExplicitReferencedDependency: true,
- parentComponentId: topLevelComponent.Component.Id,
+ parentComponentId: this.topLevelComponent.Component.Id,
isDevelopmentDependency: componentAndDevDependencyTuple.IsDevelopmentDependency,
dependencyScope: componentAndDevDependencyTuple.dependencyScope);
}
- tupleStack.Push(newTuple);
+ this.tupleStack.Push(newTuple);
}
private class GraphNodeAtLevel : GraphNode
@@ -140,7 +140,7 @@ private class GraphNodeAtLevel : GraphNode
public GraphNodeAtLevel(int level, T value)
: base(value)
{
- ParseLevel = level;
+ this.ParseLevel = level;
}
}
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs
index c7c72de52..c23328b1a 100644
--- a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs
@@ -32,15 +32,15 @@ public class MvnCliComponentDetector : FileComponentDetector
protected override async Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs)
{
- if (!await MavenCommandService.MavenCLIExists())
+ if (!await this.MavenCommandService.MavenCLIExists())
{
- Logger.LogVerbose("Skipping maven detection as maven is not available in the local PATH.");
+ this.Logger.LogVerbose("Skipping maven detection as maven is not available in the local PATH.");
return Enumerable.Empty().ToObservable();
}
- var processPomFile = new ActionBlock(MavenCommandService.GenerateDependenciesFile);
+ var processPomFile = new ActionBlock(this.MavenCommandService.GenerateDependenciesFile);
- await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest =>
+ await this.RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest =>
{
processPomFile.Post(processRequest);
});
@@ -49,7 +49,8 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest =>
await processPomFile.Completion;
- return ComponentStreamEnumerableFactory.GetComponentStreams(CurrentScanRequest.SourceDirectory, new[] { MavenCommandService.BcdeMvnDependencyFileName }, CurrentScanRequest.DirectoryExclusionPredicate)
+ return this.ComponentStreamEnumerableFactory.GetComponentStreams(this.CurrentScanRequest.SourceDirectory, new[] {
+ this.MavenCommandService.BcdeMvnDependencyFileName }, this.CurrentScanRequest.DirectoryExclusionPredicate)
.Select(componentStream =>
{
// The file stream is going to be disposed after the iteration is finished
@@ -64,7 +65,7 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest =>
Location = componentStream.Location,
Pattern = componentStream.Pattern,
},
- SingleFileComponentRecorder = ComponentRecorder.CreateSingleFileComponentRecorder(
+ SingleFileComponentRecorder = this.ComponentRecorder.CreateSingleFileComponentRecorder(
Path.Combine(Path.GetDirectoryName(componentStream.Location), "pom.xml")),
};
})
@@ -73,7 +74,7 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest =>
protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs)
{
- MavenCommandService.ParseDependenciesFile(processRequest);
+ this.MavenCommandService.ParseDependenciesFile(processRequest);
File.Delete(processRequest.ComponentStream.Location);
@@ -82,15 +83,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
private IObservable RemoveNestedPomXmls(IObservable componentStreams)
{
- List directoryItemFacades = new List();
- Dictionary directoryItemFacadesByPath = new Dictionary();
+ var directoryItemFacades = new List();
+ var directoryItemFacadesByPath = new Dictionary();
return Observable.Create(s =>
{
return componentStreams.Subscribe(
processRequest =>
{
var item = processRequest.ComponentStream;
- string currentDir = item.Location;
+ var currentDir = item.Location;
DirectoryItemFacade last = null;
do
{
@@ -135,7 +136,7 @@ private IObservable RemoveNestedPomXmls(IObservable string.Equals(Path.GetFileName(x.Location), "pom.xml", StringComparison.OrdinalIgnoreCase)) != null)
{
- Logger.LogVerbose($"Ignoring pom.xml at {item.Location}, as it has a parent pom.xml that will be processed at {current.Name}\\pom.xml .");
+ this.Logger.LogVerbose($"Ignoring pom.xml at {item.Location}, as it has a parent pom.xml that will be processed at {current.Name}\\pom.xml .");
break;
}
diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs
index 05c52dd1b..1a74c24d0 100644
--- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs
@@ -43,16 +43,16 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
contents = await reader.ReadToEndAsync();
}
- await SafeProcessAllPackageJTokens(filePath, contents, (token) =>
+ await this.SafeProcessAllPackageJTokens(filePath, contents, (token) =>
{
if (token["name"] == null || token["version"] == null)
{
- Logger.LogInfo($"{filePath} does not contain a name and/or version. These are required fields for a valid package.json file." +
- $"It and its dependencies will not be registered.");
+ this.Logger.LogInfo($"{filePath} does not contain a name and/or version. These are required fields for a valid package.json file." +
+ $"It and its dependencies will not be registered.");
return false;
}
- return ProcessIndividualPackageJTokens(filePath, singleFileComponentRecorder, token);
+ return this.ProcessIndividualPackageJTokens(filePath, singleFileComponentRecorder, token);
});
}
@@ -60,13 +60,13 @@ private async Task SafeProcessAllPackageJTokens(string sourceFilePath, string co
{
try
{
- await ProcessAllPackageJTokensAsync(contents, jtokenProcessor);
+ await this.ProcessAllPackageJTokensAsync(contents, jtokenProcessor);
}
catch (Exception e)
{
// If something went wrong, just ignore the component
- Logger.LogBuildWarning($"Could not parse Jtokens from file {sourceFilePath}.");
- Logger.LogFailedReadingFile(sourceFilePath, e);
+ this.Logger.LogBuildWarning($"Could not parse Jtokens from file {sourceFilePath}.");
+ this.Logger.LogFailedReadingFile(sourceFilePath, e);
return;
}
}
@@ -83,15 +83,15 @@ protected virtual bool ProcessIndividualPackageJTokens(string filePath, ISingleF
var name = packageJToken["name"].ToString();
var version = packageJToken["version"].ToString();
var authorToken = packageJToken["author"];
-
+
if (!SemanticVersion.TryParse(version, out _))
{
- Logger.LogWarning($"Unable to parse version \"{version}\" for package \"{name}\" found at path \"{filePath}\". This may indicate an invalid npm package component and it will not be registered.");
+ this.Logger.LogWarning($"Unable to parse version \"{version}\" for package \"{name}\" found at path \"{filePath}\". This may indicate an invalid npm package component and it will not be registered.");
return false;
}
- NpmComponent npmComponent = new NpmComponent(name, version, author: GetAuthor(authorToken, name, filePath));
-
+ var npmComponent = new NpmComponent(name, version, author: this.GetAuthor(authorToken, name, filePath));
+
singleFileComponentRecorder.RegisterUsage(new DetectedComponent(npmComponent));
return true;
}
@@ -106,12 +106,12 @@ private NpmAuthor GetAuthor(JToken authorToken, string packageName, string fileP
string authorName;
string authorEmail;
- string authorSingleStringPattern = @"^(?([^<(]+?)?)[ \t]*(?:<(?([^>(]+?))>)?[ \t]*(?:\(([^)]+?)\)|$)";
- Match authorMatch = new Regex(authorSingleStringPattern).Match(authorString);
+ var authorSingleStringPattern = @"^(?([^<(]+?)?)[ \t]*(?:<(?([^>(]+?))>)?[ \t]*(?:\(([^)]+?)\)|$)";
+ var authorMatch = new Regex(authorSingleStringPattern).Match(authorString);
/*
* for parsing author in Json Format
- * for e.g.
+ * for e.g.
* "author": {
* "name": "John Doe",
* "email": "johndoe@outlook.com",
@@ -127,25 +127,25 @@ private NpmAuthor GetAuthor(JToken authorToken, string packageName, string fileP
* for e.g.
* "author": "John Doe https://jd.com"
*/
- }
+ }
else if (authorMatch.Success)
{
authorName = authorMatch.Groups["name"].ToString().Trim();
authorEmail = authorMatch.Groups["email"].ToString().Trim();
- }
+ }
else
{
- Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered.");
+ this.Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered.");
return null;
}
if (string.IsNullOrEmpty(authorName))
{
- Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered.");
+ this.Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered.");
return null;
}
return new NpmAuthor(authorName, authorEmail);
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs
index 58a9677fb..1c9f32fa2 100644
--- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs
+++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs
@@ -49,15 +49,15 @@ public class NpmComponentDetectorWithRoots : FileComponentDetector
protected override Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs)
{
- return Task.FromResult(RemoveNodeModuleNestedFiles(processRequests)
+ return Task.FromResult(this.RemoveNodeModuleNestedFiles(processRequests)
.Where(pr =>
{
if (pr.ComponentStream.Pattern.Equals(LernaSearchPattern))
{
// Lock LernaFiles so we don't add while we are enumerating in processFiles
- lock (lernaFilesLock)
+ lock (this.lernaFilesLock)
{
- LernaFiles.Add(pr);
+ this.LernaFiles.Add(pr);
return false;
}
}
@@ -72,15 +72,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder;
var file = processRequest.ComponentStream;
- IEnumerable packageJsonComponentStream = ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(file.Location).Directory, packageJsonPattern, (name, directoryName) => false, false);
+ var packageJsonComponentStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(file.Location).Directory, packageJsonPattern, (name, directoryName) => false, false);
- bool foundUnderLerna = false;
+ var foundUnderLerna = false;
IList lernaFilesClone;
// ToList LernaFiles to generate a copy we can act on without holding the lock for a long time
- lock (lernaFilesLock)
+ lock (this.lernaFilesLock)
{
- lernaFilesClone = LernaFiles.ToList();
+ lernaFilesClone = this.LernaFiles.ToList();
}
foreach (var lernaProcessRequest in lernaFilesClone)
@@ -88,31 +88,31 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio
var lernaFile = lernaProcessRequest.ComponentStream;
// We have extra validation on lock files not found below a lerna.json
- if (PathUtilityService.IsFileBelowAnother(lernaFile.Location, file.Location))
+ if (this.PathUtilityService.IsFileBelowAnother(lernaFile.Location, file.Location))
{
foundUnderLerna = true;
break;
}
}
- await SafeProcessAllPackageJTokens(file, (token) =>
+ await this.SafeProcessAllPackageJTokens(file, (token) =>
{
if (!foundUnderLerna && (token["name"] == null || token["version"] == null || string.IsNullOrWhiteSpace(token["name"].Value()) || string.IsNullOrWhiteSpace(token["version"].Value())))
{
- Logger.LogInfo($"{file.Location} does not contain a valid name and/or version. These are required fields for a valid package-lock.json file." +
- $"It and its dependencies will not be registered.");
+ this.Logger.LogInfo($"{file.Location} does not contain a valid name and/or version. These are required fields for a valid package-lock.json file." +
+ $"It and its dependencies will not be registered.");
return false;
}
- ProcessIndividualPackageJTokens(singleFileComponentRecorder, token, packageJsonComponentStream, skipValidation: foundUnderLerna);
+ this.ProcessIndividualPackageJTokens(singleFileComponentRecorder, token, packageJsonComponentStream, skipValidation: foundUnderLerna);
return true;
});
}
private IObservable RemoveNodeModuleNestedFiles(IObservable componentStreams)
{
- List