diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..35049cb --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --package xtask --" diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..1ca7ccd --- /dev/null +++ b/.editorconfig @@ -0,0 +1,363 @@ +root = true + +# All files +[*] +indent_style = space + +# Xml files +[*.xml] +indent_size = 2 + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +tab_width = 4 + +# New line preferences +end_of_line = lf +insert_final_newline = false + +#### .NET Coding Conventions #### +[*.{cs,vb}] + +# Organize usings +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_property = false:silent + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent + +# Expression-level preferences +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_object_initializer = true:suggestion +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion + +# Field preferences +dotnet_style_readonly_field = true:warning + +# Parameter preferences +dotnet_code_quality_unused_parameters = all:suggestion + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +#### C# Coding Conventions #### +[*.cs] + +# var preferences +csharp_style_var_elsewhere = false:silent +csharp_style_var_for_built_in_types = false:silent +csharp_style_var_when_type_is_apparent = false:silent + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_lambdas = true:suggestion +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_switch_expression = true:suggestion + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:suggestion + +# Modifier preferences +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:silent + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### +[*.{cs,vb}] + +# Naming rules + +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion +dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces +dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase + +dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion +dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters +dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase + +dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods +dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties +dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.events_should_be_pascalcase.symbols = events +dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion +dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables +dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase + +dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion +dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants +dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase + +dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion +dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters +dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase + +dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields +dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion +dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields +dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase + +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase + +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums +dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase + +# Symbol specifications + +dotnet_naming_symbols.interfaces.applicable_kinds = interface +dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interfaces.required_modifiers = + +dotnet_naming_symbols.enums.applicable_kinds = enum +dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.enums.required_modifiers = + +dotnet_naming_symbols.events.applicable_kinds = event +dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.events.required_modifiers = + +dotnet_naming_symbols.methods.applicable_kinds = method +dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.methods.required_modifiers = + +dotnet_naming_symbols.properties.applicable_kinds = property +dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.properties.required_modifiers = + +dotnet_naming_symbols.public_fields.applicable_kinds = field +dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_fields.required_modifiers = + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_fields.required_modifiers = + +dotnet_naming_symbols.private_static_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_static_fields.required_modifiers = static + +dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum +dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types_and_namespaces.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +dotnet_naming_symbols.type_parameters.applicable_kinds = namespace +dotnet_naming_symbols.type_parameters.applicable_accessibilities = * +dotnet_naming_symbols.type_parameters.required_modifiers = + +dotnet_naming_symbols.private_constant_fields.applicable_kinds = field +dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_constant_fields.required_modifiers = const + +dotnet_naming_symbols.local_variables.applicable_kinds = local +dotnet_naming_symbols.local_variables.applicable_accessibilities = local +dotnet_naming_symbols.local_variables.required_modifiers = + +dotnet_naming_symbols.local_constants.applicable_kinds = local +dotnet_naming_symbols.local_constants.applicable_accessibilities = local +dotnet_naming_symbols.local_constants.required_modifiers = const + +dotnet_naming_symbols.parameters.applicable_kinds = parameter +dotnet_naming_symbols.parameters.applicable_accessibilities = * +dotnet_naming_symbols.parameters.required_modifiers = + +dotnet_naming_symbols.public_constant_fields.applicable_kinds = field +dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_constant_fields.required_modifiers = const + +dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static + +dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function +dotnet_naming_symbols.local_functions.applicable_accessibilities = * +dotnet_naming_symbols.local_functions.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascalcase.required_prefix = +dotnet_naming_style.pascalcase.required_suffix = +dotnet_naming_style.pascalcase.word_separator = +dotnet_naming_style.pascalcase.capitalization = pascal_case + +dotnet_naming_style.ipascalcase.required_prefix = I +dotnet_naming_style.ipascalcase.required_suffix = +dotnet_naming_style.ipascalcase.word_separator = +dotnet_naming_style.ipascalcase.capitalization = pascal_case + +dotnet_naming_style.tpascalcase.required_prefix = T +dotnet_naming_style.tpascalcase.required_suffix = +dotnet_naming_style.tpascalcase.word_separator = +dotnet_naming_style.tpascalcase.capitalization = pascal_case + +dotnet_naming_style._camelcase.required_prefix = _ +dotnet_naming_style._camelcase.required_suffix = +dotnet_naming_style._camelcase.word_separator = +dotnet_naming_style._camelcase.capitalization = camel_case + +dotnet_naming_style.camelcase.required_prefix = +dotnet_naming_style.camelcase.required_suffix = +dotnet_naming_style.camelcase.word_separator = +dotnet_naming_style.camelcase.capitalization = camel_case + +dotnet_naming_style.s_camelcase.required_prefix = s_ +dotnet_naming_style.s_camelcase.required_suffix = +dotnet_naming_style.s_camelcase.word_separator = +dotnet_naming_style.s_camelcase.capitalization = camel_case diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 013f2e0..8b8e4f7 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,3 +1,3 @@ # File auto-generated and managed by Devops -/.github/ @devolutions/devops +/.github/ @devolutions/devops @devolutions/architecture-maintainers /.github/dependabot.yml @devolutions/security-managers diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d6d89dd --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,26 @@ +version: 2 +updates: + - package-ecosystem: "cargo" + directory: "/" + schedule: + interval: "weekly" + assignees: + - "CBenoit" + open-pull-requests-limit: 3 + groups: + crypto: + patterns: + - "md-5" + - "md5" + - "sha1" + - "pkcs1" + - "x509-cert" + - "der" + - "*tls*" + - "*rand*" + patch: + dependency-type: "production" + update-types: + - "patch" + dev: + dependency-type: "development" \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..499a0df --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,146 @@ +name: CI + +on: + push: + branches: + - master + pull_request: + types: [ opened, synchronize, reopened ] + workflow_dispatch: + +env: + # Disable incremental compilation. CI builds are often closer to from-scratch builds, as changes + # are typically bigger than from a local edit-compile cycle. + # Incremental compilation also significantly increases the amount of IO and the size of ./target + # folder, which makes caching less effective. + CARGO_INCREMENTAL: 0 + CARGO_NET_RETRY: 10 + RUSTUP_MAX_RETRIES: 10 + RUST_BACKTRACE: short + CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse + # Cache should never takes more than a few seconds to get downloaded. + # If it does, let’s just rebuild from scratch instead of hanging "forever". + SEGMENT_DOWNLOAD_TIMEOUT_MINS: 1 + # Disabling debug info so compilation is faster and ./target folder is smaller. + CARGO_PROFILE_DEV_DEBUG: 0 + +jobs: + formatting: + name: Check formatting + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Check formatting (Rust) + run: cargo xtask rust fmt -v + + - name: Check formatting (.NET) + run: cargo xtask dotnet fmt -v + + typos: + name: Check typos + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Binary cache + uses: actions/cache@v4 + with: + path: ./.cargo/local_root/bin + key: ${{ runner.os }}-bin-${{ github.job }}-${{ hashFiles('xtask/src/bin_version.rs') }} + + - name: typos (prepare) + run: cargo xtask check install -v + + - name: typos (check) + run: cargo xtask check typos -v + + rust-checks: + name: Rust checks [${{ matrix.os }}] + runs-on: ${{ matrix.runner }} + needs: formatting + strategy: + fail-fast: false + matrix: + os: [ windows, linux, macos ] + include: + - os: windows + runner: windows-latest + - os: linux + runner: ubuntu-latest + - os: macos + runner: macos-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Rust cache + uses: Swatinem/rust-cache@v2.7.3 + + - name: Binary cache + uses: actions/cache@v4 + with: + path: ./.cargo/local_root/bin + key: ${{ runner.os }}-bin-${{ github.job }}-${{ hashFiles('xtask/src/bin_version.rs') }} + + # Compilation is separated from execution so we know exactly the time for each step. + - name: Tests (compile) + run: cargo xtask rust tests --no-run -v + - name: Tests (run) + run: cargo xtask rust tests -v + + - name: Lints + run: cargo xtask rust lints -v + + - name: Lock files + run: cargo xtask check locks -v + + dotnet-checks: + name: .NET checks [${{ matrix.os }}] + runs-on: ${{ matrix.runner }} + needs: formatting + strategy: + fail-fast: false + matrix: + os: [ windows, linux, macos ] + include: + - os: windows + runner: windows-latest + - os: linux + runner: ubuntu-latest + - os: macos + runner: macos-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Tests + run: cargo xtask dotnet tests -v + + - name: Lints + run: cargo xtask dotnet build -v + + - name: Lock files + run: cargo xtask check locks -v + + success: + name: Success + runs-on: ubuntu-latest + if: ${{ always() }} + needs: + - formatting + - typos + - rust-checks + - dotnet-checks + + steps: + - name: Check success + shell: pwsh + run: | + $results = '${{ toJSON(needs.*.result) }}' | ConvertFrom-Json + $succeeded = $($results | Where { $_ -Ne "success" }).Count -Eq 0 + exit $(if ($succeeded) { 0 } else { 1 }) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dc1f0ac --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +# Build artifacts +/target + +# Local cargo root +/.cargo/local_root + +# Editor/IDE files +*~ +/tags +.idea +.vscode +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sw? diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..36041cb --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,51 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" + +[[package]] +name = "now-proto-fuzzing" +version = "0.0.0" + +[[package]] +name = "now-proto-pdu" +version = "0.1.0" + +[[package]] +name = "now-proto-testsuite" +version = "0.0.0" + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "xshell" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e7290c623014758632efe00737145b6867b66292c42167f2ec381eb566a373d" +dependencies = [ + "xshell-macros", +] + +[[package]] +name = "xshell-macros" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32ac00cd3f8ec9c1d33fb3e7958a82df6989c42d747bd326c822b1d625283547" + +[[package]] +name = "xtask" +version = "0.0.0" +dependencies = [ + "anyhow", + "pico-args", + "xshell", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..aec415d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,106 @@ +[workspace] +resolver = "2" +members = [ + "crates/*", + "xtask", +] + +[workspace.package] +edition = "2021" +license = "MIT/Apache-2.0" +homepage = "https://github.com/Devolutions/now-proto" +repository = "https://github.com/Devolutions/now-proto" +authors = ["Devolutions Inc. "] +keywords = ["rdp", "remote-desktop", "network", "client", "protocol"] +categories = ["network-programming"] + +[workspace.dependencies] +now-proto-pdu = { version = "0.1", path = "crates/now-proto-pdu" } +now-proto-fuzzing = { version = "0.1", path = "crates/now-proto-fuzzing" } + +[profile.test.package.proptest] +opt-level = 3 + +[profile.test.package.rand_chacha] +opt-level = 3 + +[workspace.lints.rust] +# == Safer unsafe == # +unsafe_op_in_unsafe_fn = "warn" +invalid_reference_casting = "warn" + +# == Style, readability == # +elided_lifetimes_in_paths = "warn" # https://quinedot.github.io/rust-learning/dont-hide.html +absolute_paths_not_starting_with_crate = "warn" +single_use_lifetimes = "warn" +unreachable_pub = "warn" +unused_lifetimes = "warn" +unused_qualifications = "warn" +keyword_idents = "warn" +noop_method_call = "warn" + +# == Compile-time / optimization == # +unused_crate_dependencies = "warn" +unused_macro_rules = "warn" + +[workspace.lints.clippy] +# == Safer unsafe == # +undocumented_unsafe_blocks = "warn" +multiple_unsafe_ops_per_block = "warn" +transmute_ptr_to_ptr = "warn" +as_ptr_cast_mut = "warn" +cast_ptr_alignment = "warn" +fn_to_numeric_cast_any = "warn" +ptr_cast_constness = "warn" + +# == Correctness == # +cast_lossless = "warn" +cast_possible_truncation = "warn" +cast_possible_wrap = "warn" +cast_sign_loss = "warn" +float_cmp = "warn" +as_underscore = "warn" +unwrap_used = "warn" # Let’s either handle `None`, `Err` or use `expect` to give a reason. +large_stack_frames = "warn" + +# == Style, readability == # +semicolon_outside_block = "warn" # With semicolon-outside-block-ignore-multiline = true +clone_on_ref_ptr = "warn" +cloned_instead_of_copied = "warn" +trait_duplication_in_bounds = "warn" +type_repetition_in_bounds = "warn" +checked_conversions = "warn" +get_unwrap = "warn" +similar_names = "warn" # Reduce risk of confusing similar names together, and protects against typos when variable shadowing was intended. +str_to_string = "warn" +string_to_string = "warn" +std_instead_of_core = "warn" +separated_literal_suffix = "warn" +unused_self = "warn" +useless_let_if_seq = "warn" +string_add = "warn" +range_plus_one = "warn" +self_named_module_files = "warn" +partial_pub_fields = "warn" + +# == Compile-time / optimization == # +inline_always = "warn" +or_fun_call = "warn" +unnecessary_box_returns = "warn" + +# == Extra-pedantic clippy == # +collection_is_never_read = "warn" +copy_iterator = "warn" +expl_impl_clone_on_copy = "warn" +implicit_clone = "warn" +large_types_passed_by_value = "warn" +redundant_clone = "warn" +alloc_instead_of_core = "warn" +empty_drop = "warn" +return_self_not_must_use = "warn" +wildcard_dependencies = "warn" + +# == Let’s not merge unintended eprint!/print! statements in libraries == # +print_stderr = "warn" +print_stdout = "warn" +dbg_macro = "warn" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,23 @@ +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. diff --git a/NowProto.sln b/NowProto.sln new file mode 100644 index 0000000..61f7c3d --- /dev/null +++ b/NowProto.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "nugets", "nugets", "{BD6154A5-8825-4023-A6AE-CE9FCC4B073B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Devolutions.NowProto", "nugets\Devolutions.NowProto\Devolutions.NowProto.csproj", "{2EB02FFB-DC42-4217-8520-93F06E17BFC4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Devolutions.NowProto.Tests", "nugets\Devolutions.NowProto.Tests\Devolutions.NowProto.Tests.csproj", "{34912761-E8CB-4D88-A4B4-365F6DB88985}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2EB02FFB-DC42-4217-8520-93F06E17BFC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2EB02FFB-DC42-4217-8520-93F06E17BFC4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2EB02FFB-DC42-4217-8520-93F06E17BFC4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2EB02FFB-DC42-4217-8520-93F06E17BFC4}.Release|Any CPU.Build.0 = Release|Any CPU + {34912761-E8CB-4D88-A4B4-365F6DB88985}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {34912761-E8CB-4D88-A4B4-365F6DB88985}.Debug|Any CPU.Build.0 = Debug|Any CPU + {34912761-E8CB-4D88-A4B4-365F6DB88985}.Release|Any CPU.ActiveCfg = Release|Any CPU + {34912761-E8CB-4D88-A4B4-365F6DB88985}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {2EB02FFB-DC42-4217-8520-93F06E17BFC4} = {BD6154A5-8825-4023-A6AE-CE9FCC4B073B} + {34912761-E8CB-4D88-A4B4-365F6DB88985} = {BD6154A5-8825-4023-A6AE-CE9FCC4B073B} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md index 1ae4640..787fa6a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # now-proto + Devolutions::Now::Agent RDP virtual channel diff --git a/crates/now-proto-fuzzing/Cargo.toml b/crates/now-proto-fuzzing/Cargo.toml new file mode 100644 index 0000000..001348c --- /dev/null +++ b/crates/now-proto-fuzzing/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "now-proto-fuzzing" +version = "0.0.0" +edition = "2021" +description = "Provides test case generators and oracles for use with NOW protocol fuzzing" +publish = false + +[lib] +doctest = false +test = false + +[dependencies] +# arbitrary = { version = "1", features = ["derive"] } +# now-proto-pdu.workspace = true + +[lints] +workspace = true + diff --git a/crates/now-proto-fuzzing/src/generators/mod.rs b/crates/now-proto-fuzzing/src/generators/mod.rs new file mode 100644 index 0000000..0001ec2 --- /dev/null +++ b/crates/now-proto-fuzzing/src/generators/mod.rs @@ -0,0 +1,9 @@ +//! Test case generators. +//! +//! Test case generators take raw, unstructured input from a fuzzer +//! (e.g. libFuzzer) and translate that into a structured test case (e.g. a +//! valid RDP PDU). +//! +//! These are generally implementations of the `Arbitrary` trait, or some +//! wrapper over an external tool, such that the wrapper implements the +//! `Arbitrary` trait for the wrapped external tool. diff --git a/crates/now-proto-fuzzing/src/lib.rs b/crates/now-proto-fuzzing/src/lib.rs new file mode 100644 index 0000000..d12c907 --- /dev/null +++ b/crates/now-proto-fuzzing/src/lib.rs @@ -0,0 +1,12 @@ +// No need to be as strict as in production libraries +#![allow(clippy::arithmetic_side_effects)] +#![allow(clippy::cast_lossless)] +#![allow(clippy::cast_possible_truncation)] +#![allow(clippy::cast_possible_wrap)] +#![allow(clippy::cast_sign_loss)] + +// #[macro_use] +// extern crate arbitrary; + +pub mod generators; +pub mod oracles; diff --git a/crates/now-proto-fuzzing/src/oracles/mod.rs b/crates/now-proto-fuzzing/src/oracles/mod.rs new file mode 100644 index 0000000..ade833b --- /dev/null +++ b/crates/now-proto-fuzzing/src/oracles/mod.rs @@ -0,0 +1,11 @@ +//! Oracles. +//! +//! Oracles take a test case and determine whether we have a bug. For example, +//! one of the simplest oracles is to take a RDP PDU as our input test case, +//! encode and decode it, and (implicitly) check that no assertions +//! failed or segfaults happened. A more complicated oracle might compare the +//! result of two different implementations for the same thing, and +//! make sure that the two executions are observably identical (differential fuzzing). +//! +//! When an oracle finds a bug, it should report it to the fuzzing engine by +//! panicking. diff --git a/crates/now-proto-pdu/Cargo.toml b/crates/now-proto-pdu/Cargo.toml new file mode 100644 index 0000000..c192c84 --- /dev/null +++ b/crates/now-proto-pdu/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "now-proto-pdu" +version = "0.1.0" +readme = "README.md" +description = "NOW protocol PDU encoding and decoding" +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +authors.workspace = true +keywords.workspace = true +categories.workspace = true + +[lib] +doctest = false +test = false + +[lints] +workspace = true diff --git a/crates/now-proto-pdu/src/lib.rs b/crates/now-proto-pdu/src/lib.rs new file mode 100644 index 0000000..b93cf3f --- /dev/null +++ b/crates/now-proto-pdu/src/lib.rs @@ -0,0 +1,14 @@ +pub fn add(left: u64, right: u64) -> u64 { + left + right +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + let result = add(2, 2); + assert_eq!(result, 4); + } +} diff --git a/crates/now-proto-testsuite/Cargo.toml b/crates/now-proto-testsuite/Cargo.toml new file mode 100644 index 0000000..6dbbab0 --- /dev/null +++ b/crates/now-proto-testsuite/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "now-proto-testsuite" +version = "0.0.0" +edition = "2021" +description = "NOW protocol test suite" +publish = false +autotests = false + +[lib] +doctest = false +test = false + +[[test]] +name = "integration_tests" +path = "tests/main.rs" +harness = true + +[lints] +workspace = true diff --git a/crates/now-proto-testsuite/src/lib.rs b/crates/now-proto-testsuite/src/lib.rs new file mode 100644 index 0000000..63cdd0b --- /dev/null +++ b/crates/now-proto-testsuite/src/lib.rs @@ -0,0 +1,7 @@ +// No need to be as strict as in production libraries +#![allow(clippy::arithmetic_side_effects)] +#![allow(clippy::cast_lossless)] +#![allow(clippy::cast_possible_truncation)] +#![allow(clippy::cast_possible_wrap)] +#![allow(clippy::cast_sign_loss)] +#![allow(unused_crate_dependencies)] diff --git a/crates/now-proto-testsuite/tests/main.rs b/crates/now-proto-testsuite/tests/main.rs new file mode 100644 index 0000000..a67f9ea --- /dev/null +++ b/crates/now-proto-testsuite/tests/main.rs @@ -0,0 +1,14 @@ +#![allow(unused_crate_dependencies)] // false positives because there is both a library and a binary + +//! Integration Tests (IT) +//! +//! Integration tests are all contained in this single crate, and organized in modules. +//! This is to prevent `rustc` to re-link the library crates with each of the integration +//! tests (one for each *.rs file / test crate under the `tests/` folder). +//! Performance implication: https://github.com/rust-lang/cargo/pull/5022#issuecomment-364691154 +//! +//! This is also good for execution performance. +//! Cargo will run all tests from a single binary in parallel, but +//! binaries themselves are run sequentally. + +// mod now_proto; diff --git a/nugets/.gitignore b/nugets/.gitignore new file mode 100644 index 0000000..104b544 --- /dev/null +++ b/nugets/.gitignore @@ -0,0 +1,484 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/nugets/Devolutions.NowProto.Tests/Devolutions.NowProto.Tests.csproj b/nugets/Devolutions.NowProto.Tests/Devolutions.NowProto.Tests.csproj new file mode 100644 index 0000000..9e0c306 --- /dev/null +++ b/nugets/Devolutions.NowProto.Tests/Devolutions.NowProto.Tests.csproj @@ -0,0 +1,25 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + diff --git a/nugets/Devolutions.NowProto.Tests/GlobalUsings.cs b/nugets/Devolutions.NowProto.Tests/GlobalUsings.cs new file mode 100644 index 0000000..8c927eb --- /dev/null +++ b/nugets/Devolutions.NowProto.Tests/GlobalUsings.cs @@ -0,0 +1 @@ +global using Xunit; \ No newline at end of file diff --git a/nugets/Devolutions.NowProto.Tests/UnitTest1.cs b/nugets/Devolutions.NowProto.Tests/UnitTest1.cs new file mode 100644 index 0000000..4c2d020 --- /dev/null +++ b/nugets/Devolutions.NowProto.Tests/UnitTest1.cs @@ -0,0 +1,10 @@ +namespace Devolutions.NowProto.Tests; + +public class UnitTest1 +{ + [Fact] + public void Test1() + { + + } +} \ No newline at end of file diff --git a/nugets/Devolutions.NowProto/Class1.cs b/nugets/Devolutions.NowProto/Class1.cs new file mode 100644 index 0000000..33915a3 --- /dev/null +++ b/nugets/Devolutions.NowProto/Class1.cs @@ -0,0 +1,5 @@ +namespace Devolutions.NowProto; + +public class Class1 +{ +} \ No newline at end of file diff --git a/nugets/Devolutions.NowProto/Devolutions.NowProto.csproj b/nugets/Devolutions.NowProto/Devolutions.NowProto.csproj new file mode 100644 index 0000000..fa71b7a --- /dev/null +++ b/nugets/Devolutions.NowProto/Devolutions.NowProto.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..3d572e0 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.82.0" +components = ["rustfmt", "clippy"] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..2d87bb0 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,4 @@ +max_width = 120 +reorder_imports = true +imports_granularity = "Module" +group_imports = "StdExternalCrate" diff --git a/typos.toml b/typos.toml new file mode 100644 index 0000000..ca63b60 --- /dev/null +++ b/typos.toml @@ -0,0 +1,24 @@ +# Typos CLI configuration file +# ============================ +# ## Running `typos-cli`. +# Execute `cargo xtask check typos` to run `typos-cli` with the same configuration as on CI. +# +# ## Updating `typos-cli`. +# Please regularly update `typos-cli` to the latest version. If a new version is available, please +# update the version string in `xtask\src\bin_version.rs`. +# +# ## How to properly fix `typos-cli` errors: +# 1. If a typo is obvious: just fix it. +# 2. False-positive in the binary/test asset/generated file: add it to `extend-exclude` glob list. +# 3. False-positive in the source code: (in order of preference) +# 3.1. Place correction in `extend-identifiers` if a false-positive is in the identifier name. +# 3.2. Place correction in `extend-words` if a false-positive is in the arbitrary word (docs, +# comments, etc.) or text was not recognized as an identifier. +# 3.3. Place regex in `extend-ignore-re` if the correction cannot be expressed as a single word. +# 3.4. Last resort: add file ignore to `extend-exclude` list. + +[files] +extend-exclude = [] + +[default] +extend-ignore-re = [] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..21880cc --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "xtask" +version = "0.0.0" +edition = "2021" +publish = false + +[[bin]] +name = "xtask" +test = false + +[dependencies] +anyhow = "1" +pico-args = "0.5" +xshell = "0.2" + +[lints] +workspace = true + diff --git a/xtask/README.md b/xtask/README.md new file mode 100644 index 0000000..7e8c35a --- /dev/null +++ b/xtask/README.md @@ -0,0 +1,3 @@ +# IronRDP project automation + +Free-form automation following [`cargo xtask`](https://github.com/matklad/cargo-xtask) specification. diff --git a/xtask/src/bin_install.rs b/xtask/src/bin_install.rs new file mode 100644 index 0000000..ad01e05 --- /dev/null +++ b/xtask/src/bin_install.rs @@ -0,0 +1,87 @@ +use xshell::{cmd, Shell}; + +use crate::{local_bin, CARGO, LOCAL_CARGO_ROOT}; + +pub struct CargoPackage { + pub name: &'static str, + pub binary_name: &'static str, + pub version: &'static str, +} + +impl CargoPackage { + pub const fn new(name: &'static str, version: &'static str) -> Self { + Self { + name, + binary_name: name, + version, + } + } + + pub const fn with_binary_name(self, name: &'static str) -> Self { + Self { + binary_name: name, + ..self + } + } +} + +pub fn cargo_install(sh: &Shell, package: &CargoPackage) -> anyhow::Result<()> { + let package_name = package.name; + let package_version = package.version; + + if is_installed(sh, package) { + trace!("{package_name} is already installed"); + return Ok(()); + } + + if cargo_binstall_is_available(sh) { + trace!("cargo-binstall is available"); + cmd!( + sh, + "{CARGO} binstall --no-confirm --root {LOCAL_CARGO_ROOT} {package_name}@{package_version}" + ) + .run()?; + } else { + trace!("Install {package_name} using cargo install"); + // Install in debug because it's faster to compile and we typically don't need execution speed anyway. + cmd!( + sh, + "{CARGO} install --debug --locked --root {LOCAL_CARGO_ROOT} {package_name}@{package_version}" + ) + .run()?; + } + + Ok(()) +} + +fn cargo_binstall_is_available(sh: &Shell) -> bool { + cmd!(sh, "{CARGO} binstall -h") + .quiet() + .ignore_stderr() + .ignore_stdout() + .run() + .is_ok() +} + +/// Checks if a binary is installed in local root +pub fn is_installed(sh: &Shell, package: impl GetBinaryName) -> bool { + let path = local_bin().join(package.binary_name()); + sh.path_exists(&path) || sh.path_exists(path.with_extension("exe")) +} + +#[doc(hidden)] +pub trait GetBinaryName { + fn binary_name(self) -> &'static str; +} + +impl GetBinaryName for &CargoPackage { + fn binary_name(self) -> &'static str { + self.binary_name + } +} + +impl GetBinaryName for &'static str { + fn binary_name(self) -> &'static str { + self + } +} diff --git a/xtask/src/bin_version.rs b/xtask/src/bin_version.rs new file mode 100644 index 0000000..2ef3f5a --- /dev/null +++ b/xtask/src/bin_version.rs @@ -0,0 +1,6 @@ +// We pin the binaries to specific versions so we use the same artifact everywhere. +// Hash of this file is used in CI for caching. + +use crate::bin_install::CargoPackage; + +pub const TYPOS_CLI: CargoPackage = CargoPackage::new("typos-cli", "1.28.2").with_binary_name("typos"); diff --git a/xtask/src/check.rs b/xtask/src/check.rs new file mode 100644 index 0000000..a7341e9 --- /dev/null +++ b/xtask/src/check.rs @@ -0,0 +1,47 @@ +use crate::prelude::*; + +pub fn typos(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("TYPOS-CLI"); + + if !is_installed(sh, "typos") { + anyhow::bail!("`typos-cli` binary is missing. Please run `cargo xtask check install`."); + } + + cmd!(sh, "typos").run()?; + + println!("All good!"); + Ok(()) +} + +pub fn install(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("TYPOS-CLI-INSTALL"); + + cargo_install(sh, &TYPOS_CLI)?; + + Ok(()) +} + +pub fn lock_files(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("CHECK-LOCKS"); + + // Note that we can’t really use the --locked option of cargo, because to + // run xtask, we need to compile it using cargo first, and thus the lock + // files are already "refreshed" as far as cargo is concerned. Instead, + // this task will check for modifications to the lock files using git-status + // porcelain. The side benefit is that we can check for npm lock files too. + + const LOCK_FILES: &[&str] = &["Cargo.lock"]; + + let output = cmd!(sh, "git status --porcelain --untracked-files=no") + .args(LOCK_FILES) + .read()?; + + if !output.is_empty() { + cmd!(sh, "git status").run()?; + anyhow::bail!("one or more lock files are changed, you should commit those"); + } + + println!("All good!"); + + Ok(()) +} diff --git a/xtask/src/clean.rs b/xtask/src/clean.rs new file mode 100644 index 0000000..42851b7 --- /dev/null +++ b/xtask/src/clean.rs @@ -0,0 +1,23 @@ +use crate::prelude::*; + +pub fn workspace(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("CLEAN"); + + println!("Remove wasm package folder…"); + sh.remove_path("./crates/ironrdp-web/pkg")?; + println!("Done."); + + println!("Remove npm folders…"); + sh.remove_path("./web-client/iron-remote-gui/node_modules")?; + sh.remove_path("./web-client/iron-remote-gui/dist")?; + sh.remove_path("./web-client/iron-svelte-client/node_modules")?; + println!("Done."); + + println!("Remove local cargo root folder…"); + sh.remove_path("./.cargo/local_root")?; + println!("Done."); + + cmd!(sh, "{CARGO} clean").run()?; + + Ok(()) +} diff --git a/xtask/src/cli.rs b/xtask/src/cli.rs new file mode 100644 index 0000000..cb803fd --- /dev/null +++ b/xtask/src/cli.rs @@ -0,0 +1,91 @@ +const HELP: &str = "\ +cargo xtask + +USAGE: + cargo xtask [OPTIONS] [TASK] + +FLAGS: + -h, --help Prints help information + -v, --verbose Prints additional execution traces + +TASKS: + bootstrap Install all requirements for development + check install Install all requirements for check tasks + check locks Check for dirty or staged lock files not yet committed + check typos Check for typos in the codebase + ci Run all checks required on CI + clean Clean workspace + dotnet build Build the .NET packages + dotnet fmt Check formatting for .NET packages + dotnet tests Compile .NET tests and run them + rust fmt Check formatting for Rust crates + rust lints Check lints + rust tests [--no-run] Compile Rust tests and, unless specified otherwise, run them +"; + +pub fn print_help() { + println!("{HELP}"); +} + +pub struct Args { + pub verbose: bool, + pub action: Action, +} + +pub enum Action { + Bootstrap, + CheckInstall, + CheckLocks, + CheckTypos, + Ci, + Clean, + DotnetFmt, + DotnetBuild, + DotnetTests, + RustFmt, + RustLints, + RustTests { no_run: bool }, + ShowHelp, +} + +pub fn parse_args() -> anyhow::Result { + let mut args = pico_args::Arguments::from_env(); + + let action = if args.contains(["-h", "--help"]) { + Action::ShowHelp + } else { + match args.subcommand()?.as_deref() { + Some("bootstrap") => Action::Bootstrap, + Some("check") => match args.subcommand()?.as_deref() { + Some("locks") => Action::CheckLocks, + Some("typos") => Action::CheckTypos, + Some("install") => Action::CheckInstall, + Some(unknown) => anyhow::bail!("unknown check action: {unknown}"), + None => Action::ShowHelp, + }, + Some("rust") => match args.subcommand()?.as_deref() { + Some("fmt") => Action::RustFmt, + Some("lints") => Action::RustLints, + Some("tests") => Action::RustTests { + no_run: args.contains("--no-run"), + }, + Some(unknown) => anyhow::bail!("unknown check action: {unknown}"), + None => Action::ShowHelp, + }, + Some("dotnet") => match args.subcommand()?.as_deref() { + Some("fmt") => Action::DotnetFmt, + Some("build") => Action::DotnetBuild, + Some("tests") => Action::DotnetTests, + Some(unknown) => anyhow::bail!("unknown check action: {unknown}"), + None => Action::ShowHelp, + }, + Some("ci") => Action::Ci, + Some("clean") => Action::Clean, + None | Some(_) => Action::ShowHelp, + } + }; + + let verbose = args.contains(["-v", "--verbose"]); + + Ok(Args { verbose, action }) +} diff --git a/xtask/src/dotnet.rs b/xtask/src/dotnet.rs new file mode 100644 index 0000000..1404ba4 --- /dev/null +++ b/xtask/src/dotnet.rs @@ -0,0 +1,40 @@ +use crate::prelude::*; + +pub fn fmt(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("DOTNET-FORMATTING"); + + let output = cmd!(sh, "dotnet format --verify-no-changes").ignore_status().output()?; + + if !output.status.success() { + anyhow::bail!("Bad formatting, please run 'dotnet format'"); + } + + println!("All good!"); + + Ok(()) +} + +pub fn build(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("DOTNET-BUILD"); + + cmd!(sh, "dotnet build").run()?; + + if is_verbose() { + list_files(sh, "./nugets/Devolutions.NowProto/bin/Debug/net8.0") + .context("failed to list artifacts generated by dotnet build")?; + } + + println!("All good!"); + + Ok(()) +} + +pub fn tests_run(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("DOTNET-TESTS-RUN"); + + cmd!(sh, "dotnet test").run()?; + + println!("All good!"); + + Ok(()) +} diff --git a/xtask/src/macros.rs b/xtask/src/macros.rs new file mode 100644 index 0000000..1e40f9e --- /dev/null +++ b/xtask/src/macros.rs @@ -0,0 +1,7 @@ +macro_rules! trace { + ($($arg:tt)*) => {{ + if $crate::is_verbose() { + eprintln!($($arg)*); + } + }}; +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..0da9c95 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,180 @@ +#![allow(clippy::print_stdout)] +#![allow(clippy::print_stderr)] +#![allow(clippy::unwrap_used)] +#![allow(unreachable_pub)] + +#[macro_use] +mod macros; + +mod bin_install; +mod bin_version; +mod check; +mod clean; +mod cli; +mod dotnet; +mod prelude; +mod rust; +mod section; + +use std::path::{Path, PathBuf}; + +use xshell::Shell; + +use crate::cli::Action; + +#[cfg(target_os = "windows")] +pub const LOCAL_CARGO_ROOT: &str = ".cargo\\local_root\\"; +#[cfg(not(target_os = "windows"))] +pub const LOCAL_CARGO_ROOT: &str = ".cargo/local_root/"; + +pub const CARGO: &str = env!("CARGO"); + +fn main() -> anyhow::Result<()> { + let args = match cli::parse_args() { + Ok(args) => args, + Err(e) => { + cli::print_help(); + return Err(e); + } + }; + + set_verbose(args.verbose); + + let sh = new_shell()?; + + match args.action { + Action::ShowHelp => cli::print_help(), + Action::Bootstrap => { + check::install(&sh)?; + + if is_verbose() { + list_files(&sh, local_bin())?; + } + } + Action::CheckInstall => { + check::install(&sh)?; + } + Action::CheckLocks => check::lock_files(&sh)?, + Action::CheckTypos => { + check::typos(&sh)?; + } + Action::Ci => { + rust::fmt(&sh)?; + rust::tests_compile(&sh)?; + rust::tests_run(&sh)?; + rust::lints(&sh)?; + + dotnet::fmt(&sh)?; + dotnet::build(&sh)?; + dotnet::tests_run(&sh)?; + + check::lock_files(&sh)?; + check::typos(&sh)?; + } + Action::Clean => clean::workspace(&sh)?, + Action::DotnetFmt => dotnet::fmt(&sh)?, + Action::DotnetBuild => dotnet::build(&sh)?, + Action::DotnetTests => dotnet::tests_run(&sh)?, + Action::RustFmt => rust::fmt(&sh)?, + Action::RustLints => rust::lints(&sh)?, + Action::RustTests { no_run } => { + if no_run { + rust::tests_compile(&sh)?; + } else { + rust::tests_run(&sh)?; + } + } + } + + Ok(()) +} + +fn new_shell() -> anyhow::Result { + let sh = Shell::new()?; + + sh.change_dir(project_root()); + create_folders(&sh)?; + update_env_path(&sh)?; + + Ok(sh) +} + +fn project_root() -> PathBuf { + Path::new(&env!("CARGO_MANIFEST_DIR")) + .ancestors() + .nth(1) + .unwrap() + .to_path_buf() +} + +fn update_env_path(sh: &Shell) -> anyhow::Result<()> { + use anyhow::Context as _; + + let original_path = sh.var_os("PATH").context("PATH variable")?; + + let paths_to_add = vec![sh.current_dir().join(local_bin())]; + + let mut new_path = std::ffi::OsString::new(); + + for path in paths_to_add { + trace!("Add {} to PATH", path.display()); + new_path.push(path.as_os_str()); + + #[cfg(target_os = "windows")] + new_path.push(";"); + #[cfg(not(target_os = "windows"))] + new_path.push(":"); + } + + new_path.push(original_path); + trace!("New PATH: {}", new_path.to_string_lossy()); + + sh.set_var("PATH", new_path); + + Ok(()) +} + +fn create_folders(sh: &Shell) -> anyhow::Result<()> { + use anyhow::Context as _; + + sh.create_dir(LOCAL_CARGO_ROOT) + .context(format!("create directory: {LOCAL_CARGO_ROOT}"))?; + + let local_bin = local_bin(); + sh.create_dir(&local_bin) + .context(format!("create directory: {}", local_bin.display()))?; + + Ok(()) +} + +pub fn local_cargo_root() -> PathBuf { + PathBuf::from(LOCAL_CARGO_ROOT) +} + +pub fn local_bin() -> PathBuf { + let mut path = local_cargo_root(); + path.push("bin"); + path +} + +static VERBOSE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); + +pub fn set_verbose(value: bool) { + VERBOSE.store(value, core::sync::atomic::Ordering::Release); +} + +pub fn is_verbose() -> bool { + VERBOSE.load(core::sync::atomic::Ordering::Acquire) +} + +pub fn list_files(sh: &Shell, path: impl AsRef) -> anyhow::Result<()> { + let path = path.as_ref(); + + eprintln!("Listing folder {}:", path.display()); + + for file in sh.read_dir(path)? { + eprintln!("- {}", file.display()); + } + + Ok(()) +} diff --git a/xtask/src/prelude.rs b/xtask/src/prelude.rs new file mode 100644 index 0000000..7480194 --- /dev/null +++ b/xtask/src/prelude.rs @@ -0,0 +1,7 @@ +pub use anyhow::Context as _; +pub use xshell::{cmd, Shell}; + +pub use crate::bin_install::{cargo_install, is_installed}; +pub use crate::bin_version::*; +pub use crate::section::Section; +pub use crate::{is_verbose, list_files, CARGO}; diff --git a/xtask/src/rust.rs b/xtask/src/rust.rs new file mode 100644 index 0000000..4448d52 --- /dev/null +++ b/xtask/src/rust.rs @@ -0,0 +1,49 @@ +use crate::prelude::*; + +pub fn fmt(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("RUST-FORMATTING"); + + let output = cmd!(sh, "{CARGO} fmt --all -- --check").ignore_status().output()?; + + if !output.status.success() { + anyhow::bail!("Bad formatting, please run 'cargo +stable fmt --all'"); + } + + println!("All good!"); + + Ok(()) +} + +pub fn lints(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("RUST-LINTS"); + + cmd!( + sh, + "{CARGO} clippy --workspace --all-targets --locked --keep-going -- -D warnings" + ) + .run()?; + + println!("All good!"); + + Ok(()) +} + +pub fn tests_compile(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("RUST-TESTS-COMPILE"); + + cmd!(sh, "{CARGO} test --workspace --locked --no-run").run()?; + + println!("All good!"); + + Ok(()) +} + +pub fn tests_run(sh: &Shell) -> anyhow::Result<()> { + let _s = Section::new("RUST-TESTS-RUN"); + + cmd!(sh, "{CARGO} test --workspace --locked").run()?; + + println!("All good!"); + + Ok(()) +} diff --git a/xtask/src/section.rs b/xtask/src/section.rs new file mode 100644 index 0000000..cf5ce59 --- /dev/null +++ b/xtask/src/section.rs @@ -0,0 +1,30 @@ +use std::time::Instant; + +pub struct Section { + name: &'static str, + start: Instant, +} + +impl Section { + pub fn new(name: &'static str) -> Section { + flush_all(); + eprintln!("::group::{name}"); + let start = Instant::now(); + Self { name, start } + } +} + +impl Drop for Section { + fn drop(&mut self) { + flush_all(); + eprintln!("{}: {:.2?}", self.name, self.start.elapsed()); + eprintln!("::endgroup::"); + } +} + +fn flush_all() { + use std::io::{self, Write as _}; + + let _ = io::stdout().flush(); + let _ = io::stderr().flush(); +}